简体   繁体   English

IE上的Ajax请求错误

[英]Ajax request ERROR on IE

I have a small problem on IE browser (actually on Google Chrome too) I have this js code 我在IE浏览器上有一个小问题(实际上也在Google Chrome上),我有此js代码

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 在Firefox中,此代码效果很好,但在IE和Google Chrome浏览器中却无效,似乎该行给出了错误

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. 由于Ajax是异步的,因此您需要在onreadystatechange代码中处理代码和响应。 Try w3schools examples 尝试w3schools示例

It looks like you are sending the request and just after that reading the responseXML, this must be causing problems 看起来您正在发送请求,并且在读取responseXML之后,这一定会引起问题

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? 您为什么不部署jQuery? Comes with optimised AJAX stack and no need to do browser-specific sniffing. 带有优化的AJAX堆栈 ,无需进行特定于浏览器的嗅探。 You'd indeed hit more app weight over library inclusion, but it's surely well worth it. 确实,应用程序在库包含方面的作用更大,但是绝对值得。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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