开发者

IE8 AJAX GET setRequestHeaders not working unless params provided in URL

开发者 https://www.devze.com 2022-12-27 18:17 出处:网络
I\'m trying to create an AJAX request in IE8. var xhr = new ActiveXObject( \'Msxml2.XMLHTTP\' ); xhr.open( \'GET\', \'/ajax/\' );

I'm trying to create an AJAX request in IE8.

var xhr = new ActiveXObject( 'Msxml2.XMLHTTP' );
xhr.open( 'GET', '/ajax/' );
// Required header for Django to detect AJAX request
xhr.setRequestHeader( 'X-Requested-With', 'XMLHttpRequest' );
xhr.onreadystatechange = function() {
   if ( this.readyState == 4 ) console.log(this.responseText); 
}
xhr.send( null );

This works perfectly fine in Firefox, Chrome, Safari. In IE8 however, all of my AJAX test requests work EXCEPT for ones where I'm p开发者_运维百科erforming GETs without any query string params (such as the one above). POSTs work without question, and GET requests only work whenever I include query strings in the URL, like this:

xhr.open( 'GET', '/ajax/?foo=bar' )

I'm also 110% positive that my server code is handling these requests appropriately, so, this stumps me completely.

Does anyone have any clue as to what might be causing this?


The standards specify that GET requests have (a) query parameter(s). My guess is that MSIE8 is acting appropriately in this case and the other browsers are 'letting it slide'.

If your intent is to load a page, you could send a GET request to a file, which then includes/freads/whatever the content file and sends it back. In this case you would have an intermediary file that includes whatever page is sent as a parameter (e.g., ?foo=bar.)

In any case, I would use jQuery to pick the corrent HTTP object, else you'll be having to do something like this for full compatibility:

var XMLHttpArray = [                        
    function() {return new XMLHttpRequest();},
    function() {return new ActiveXObject("Msxml2.XMLHTTP");},
    function() {return new ActiveXObject("Msxml2.XMLHTTP");},
    function() {return new ActiveXObject("Microsoft.XMLHTTP");}     
];

function XMLHTTPObject(){   
    var xmlhttp = false;
    for(var i=0; i<XMLHttpArray.length; i++){
            try{
                    xmlhttp = XMLHttpArray[i]();
            }catch(e){
                    continue;
            }
            break;
    }
    return xmlhttp;     
};

var http = XMLHTTPObject();
http.open(...);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号