开发者

Ajax request ERROR on IE

开发者 https://www.devze.com 2023-01-03 10:29 出处:网络
I have a small problem on IE browser (actually on Google Chrome too) I have this js code function createDoc(url) {

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 XM开发者_开发问答LHttpRequest();
    } 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.

0

精彩评论

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