Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

ajax - Cannot properly set the Accept HTTP header with jQuery

I'm trying to set the Accept HTTP header to "text/xml" with this jquery code:

$.ajax({
    beforeSend: function(req) {
        req.setRequestHeader("Accept", "text/xml");
    },
    type: "GET",
    url: "[proper url]",
    contentType: "text/plain; charset=utf-8",
    dataType: ($.browser.msie) ? "text" : "xml",
    username: '---',
    password: '-------',                                
    success: function(data) {
        var xml;
        if (typeof data == "string") {
            alert("Data is string:" + data);
            xml = new ActiveXObject("Microsoft.XMLDOM");
            xml.async = false;
            xml.loadXML(data);
        } else {
            xml = data;
            alert("Data is not string:" + $(xml).text());
        }
        // Returned data available in object "xml"
        //alert("Status is: " + xml.statusText);
        $("#ingest_history").html($(xml).text());
    }              
});

In firefox it works great.

But in IE, the value that I am trying to set for the Accept header seems to get appended onto the end so it becomes: Accept: */*, text/xml. This causes my ajax call to return the html version as opposed to the xml version which I want.

Does anybody know how to properly set/clear the Accept header in IE 8?

Updated: For some reason the asterisks weren't appearing as I entered them. The Accept Header in IE appears to be: Accept: */*, text/xml.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I also had trouble with this, not just in IE but also in Chrome and Safari using jQuery 1.6.2. This solution appears to work as intended in all browsers I've tried (Chrome, Safari, IE, Firefox).

$.ajax({
    headers: { 
        Accept : "text/plain; charset=utf-8",
        "Content-Type": "text/plain; charset=utf-8"
    },
    data: "data",
    success : function(response) {
        ...
    }
})

Try that if this is still giving you trouble.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...