burnt1ce
burnt1ce

Reputation: 14897

jQuery: How can I output content of an XML document to a node?

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 = "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?
        }
    }
});

Upvotes: 0

Views: 835

Answers (2)

jmkeyes
jmkeyes

Reputation: 3771

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.

Upvotes: 0

H&#229;vard
H&#229;vard

Reputation: 10080

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.

Upvotes: 1

Related Questions