【问题标题】:XMLHttpRequest() Not Working with IEXMLHttpRequest() 不适用于 IE
【发布时间】:2012-03-28 07:31:52
【问题描述】:

下面的脚本在 Firefox 和 Chrome 上运行良好,但我似乎无法让它与 ie 一起使用,尝试了所有方法,甚至降低了浏览器的安全性,看看是否会阻止它,但我仍然无法让它工作.

function postData() {

    var http = new XMLHttpRequest();

    var url = "/scripts/remove_fr.php";

    var params = "";

    http.open("GET", url, true);



    //Send the proper header information along with the request

    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    http.setRequestHeader("Content-length", params.length);

    http.setRequestHeader("Connection", "close");



    http.onreadystatechange = function() { //Call a function when the state changes.

        if(http.readyState == 4 && http.status == 200) {



        }

    }



    http.send(params);



}



    $("#qwerty").click(function () {

      $('#qwerty').remove();

    });



</script>

【问题讨论】:

  • IE 版本?错误?什么不工作?发生了什么?

标签: javascript jquery xml ajax


【解决方案1】:

在IE7以下,它使用ActiveXObject对象而不是XMLHttpRequest 所以你的代码应该是这样的:

function postData() {
    var http;

    if (window.XMLHttpRequest) {
         // code for IE7+, Firefox, Chrome, Opera, Safari
         http = new XMLHttpRequest();
    }
    else {
         // code for IE6, IE5
         http = new ActiveXObject("Microsoft.XMLHTTP");
    }
    var url = "/scripts/remove_fr.php";
    var params = "";
    http.open("GET", url, true);

   //Send the proper header information along with the request
   http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   http.setRequestHeader("Content-length", params.length);
   http.setRequestHeader("Connection", "close");
   http.onreadystatechange = function() { //Call a function when the state changes.
       if(http.readyState == 4 && http.status == 200) {

       }
   }
   http.send(params);
}

【讨论】:

    【解决方案2】:

    你能试试这段代码吗,这会得到基于浏览器的XMLHttpRequest。

    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    

    详情请参考链接w3schools

    【讨论】:

      【解决方案3】:

      您已经在使用 jQuery,所以请使用jQuery's AJAX utility functions!不要尝试自己动手; XMLHttpRequest API 又丑又烦人。

      我想提供示例代码,但现在你所拥有的只是:

      $.get("/scripts/remove_fr.php");
      

      这不是一个例子。 ;)

      【讨论】:

        猜你喜欢
        • 2015-01-31
        • 1970-01-01
        • 2021-06-22
        • 2012-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-08
        • 2011-06-10
        相关资源
        最近更新 更多