简体   繁体   中英

Ajax request ERROR on IE

I have a small problem on IE browser (actually on Google Chrome too) I have this js code

function createDoc(url) {
    var xhttp = ajaxRequest();
    var currentLocationBase = window.location.href;
    currentLocationBase = currentLocationBase.substr(0,currentLocationBase.lastIndexOf("/") + 1);
    var u  = currentLocationBase + url;

    xhttp.open("GET", u, false);
    xhttp.send(null);

    var xml = xhttp.responseXML;
    return xml;
}

/**
* Builds an AJAX reques handler.
*
* @return The handler.
*/
function ajaxRequest() {
    var xhttp = null;
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject){     
        // Internet Explorer 5/6
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
    }
    return xhttp;
}

In Firefox this code works great, but not in IE and Google Chrome Seems that the error is given at the line

xhttp.open("GET", u, false);

Can anyone help me to understand what i'm doing wrong? Thanks

As the Ajax is async you need to handle the code and response in the onreadystatechange code. Try w3schools examples

It looks like you are sending the request and just after that reading the responseXML, this must be causing problems

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();

Why don't you deploy jQuery? Comes with optimised AJAX stack and no need to do browser-specific sniffing. You'd indeed hit more app weight over library inclusion, but it's surely well worth it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM