简体   繁体   English

XMLHttpRequest仅在IE中有效

[英]XMLHttpRequest only works in IE

I am using the XMLHttpRequest object for my AJAX calls which has been working fine across browsers with a callback handler I have created to return JSON based on the request type and arguments etc. 我将XMLHttpRequest对象用于我的AJAX调用,该对象已在浏览器中正常运行,该浏览器具有我创建的基于请求类型和参数等返回JSON的回调处理程序。

But I am now integrating an external RESTful API to return a JSON string and for some reason it only works for me in IE (tested in IE 8). 但是我现在正在集成一个外部RESTful API以返回JSON字符串,由于某种原因,它仅在IE中对我有效(在IE 8中进行了测试)。 Using fiddler 2 I have determined that the API is returning the correct data. 使用提琴手2,我确定API返回了正确的数据。

I get the XMLHttpRequest.readyState of 4 but XMLHttpRequest.status only returns 0 for Chrome, Safari and FF. 我得到的XMLHttpRequest.readyState为4,但是XMLHttpRequest.status对于Chrome,Safari和FF只返回0。 I read that sometimes when using a local server (test server) you always get a status of zero so I bypassed my check for status but still got a blank string for XMLHttpRequest.responseText. 我读到,有时在使用本地服务器(测试服务器)时,状态总是为零,因此我绕过了状态检查,但对于XMLHttpRequest.responseText仍然是空白字符串。

function ajaxRequest(requestType,url) {

    var xmlhttp;

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function()
    {

        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            switch (requestType)
            {
                case 5:
                    //Home postcode search
                    showAddresses("home", xmlhttp.responseText);
                    break;          
            }
        }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

You should upgrade to jQuery as it will handle this request for nearly all browsers. 您应该升级到jQuery,因为它将处理几乎所有浏览器的请求。 But if you really want to know how to use XMLHttpRequest across all browsers, here's some code that seems to do the trick: https://github.com/ilinsky/xmlhttprequest/blob/master/XMLHttpRequest.js 但是,如果您真的想知道如何在所有浏览器中使用XMLHttpRequest,那么以下代码似乎可以解决问题: https : //github.com/ilinsky/xmlhttprequest/blob/master/XMLHttpRequest.js

Or, just pick apart jQuery's implementation. 或者,仅选择jQuery的实现。

http://api.jquery.com/category/ajax/ http://api.jquery.com/category/ajax/

Hope this helps. 希望这可以帮助。

My issue was that I was using an external API and xmlHttpRequest only allows you to makes calls on the same server. 我的问题是我使用的是外部API,而xmlHttpRequest只允许您在同一服务器上进行调用。 I moved my data call into my server code and got the response from my callback handling page instead of going straight out to the API. 我将数据调用移到服务器代码中,并从回调处理页面获得响应,而不是直接进入API。

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

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