2011-04-20 4 views
0

성공 이벤트 처리기에서 XML 문서의 내용을 $ (this)로 출력 할 수 있습니까?jQuery : XML 문서의 내용을 노드로 어떻게 출력 할 수 있습니까?

var useJson = false; 

var acceptHeader; 
if (useJson) { 
    acceptHeader = "application/json"; 
} else { 
    acceptHeader = "text/xml" 
} 


$.ajax({ 
    url: '<%= Url.Action("GetAllCategories") %>', 
    beforeSend: function (req) { 
     req.setRequestHeader("Accept", acceptHeader); 
    }, 
    type: 'POST', 
    accepts: "application/json", 

    context: $("#divGetAllCategories"), 
    contentType: 'application/json; charset=utf-8', 
    error: function (data) { 
     $("html").html(data.responseText); 
    }, 
    success: function (data) { 
     if (useJson) { 
      $(this).text(JSON.stringify(data)); 
     } 
     else { 
      //How do i insert xml data into $(this) as text? 
     } 
    } 
}); 

답변

1

XHR 객체의 원시 데이터 가져 오기 : 이해하면

success: function (data, textStatus, jqXHR) { 
    $(this).text(jqXHR.responseText); 
} 

:

success: function (data, textStatus, jqXHR) { 
    if (useJson) { 
     $(this).text(JSON.stringify(data)); 
    } 
    else { 
     $(this).text(jqXHR.responseText); 
    } 
} 

당신은뿐만 아니라 JSON이 작업을 수행 할 수 있으므로 코드가 단축 될 수 있습니다 너의 의도를 바르게.

+0

도움 주셔서 감사합니다. :) – burnt1ce

0

이 경우 XML 응답과 JSON 응답의 두 가지 AJAX 처리기를 설정했습니다. 두 가지를 섞으 려하지 말고 하나 또는 다른 것을 활성화하고 직접 따라하십시오.

콘텐츠를 삽입하려면 jQuery의 .text()을 사용하십시오. JSON 또는 XML 응답을 텍스트로 변환하려면 JSON.stringify() 또는 .responseText을 각각 사용하십시오.

+0

. 응답 텍스트는 세 번째 콜백 매개 변수 (Harpyon의 예에서는 jqXHR 매개 변수)에서만 작동합니다. 감사! – burnt1ce

관련 문제