How can i output the content of an XML document to $(this) in the success event handler?
var useJson = false;
var acceptHeader;
if (useJson) {
acceptHeader = "applicat开发者_运维技巧ion/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?
}
}
});
Fetch the raw data from the XHR
object:
success: function (data, textStatus, jqXHR) {
if (useJson) {
$(this).text(JSON.stringify(data));
}
else {
$(this).text(jqXHR.responseText);
}
}
You can do this for JSON as well, so your code can be shortened to:
success: function (data, textStatus, jqXHR) {
$(this).text(jqXHR.responseText);
}
If I understand your intentions correctly.
In this case, I'd set up two different AJAX handlers for the different content of responses: one for XML and one for JSON. Instead of trying to mix the two, activate one or the other and follow through with it directly.
To insert the content use jQuery's .text()
. To convert a JSON or XML response to text, use JSON.stringify()
or the .responseText
respectively.
精彩评论