简体   繁体   English

XMLHttpRequest 状态 0(响应文本为空)

[英]XMLHttpRequest status 0 (responseText is empty)

Cannot get data with XMLHttpRequest (status 0 and responseText is empty):无法使用 XMLHttpRequest 获取数据(状态 0 且 responseText 为空):

xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","http://www.w3schools.com/XML/cd_catalog.xml", true);
xmlhttp.onreadystatechange=function() 
{
  if(xmlhttp.readyState==4)
    alert("status " + xmlhttp.status);
}
xmlhttp.send();

It alerts "status 0".它提醒“状态 0”。

The same situation with the localhost request (cd_catalog.xml is saved as a local file)与localhost请求相同的情况(cd_catalog.xml保存为本地文件)

xmlhttp.open("GET","http://localhost/cd_catalog.xml", true);

But with the localhost IP request但是使用本地主机 IP 请求

xmlhttp.open("GET","http://127.0.0.1/cd_catalog.xml", true);

and with the local file request并使用本地文件请求

xmlhttp.open("GET","cd_catalog.xml", true);

everything is OK (status 200)一切正常(状态 200)

What can cause the problem (status=0) with the online request?什么会导致在线请求出现问题(状态=0)?

PS: Live HTTP Headers shows that everything is OK in all 4 cases: PS:Live HTTP Headers 显示在所有 4 种情况下一切正常:

HTTP/1.1 200 OK
  Content-Length: 4742

PS2: Apache local web server on VMWare (host OS Win7, Guest OS Ubuntu, Network adapter – NAT). PS2:VMWare 上的 Apache 本地 Web 服务器(主机操作系统 Win7、来宾操作系统 Ubuntu、网络适配器 – NAT)。 Browser – Firefox.浏览器 - 火狐。

status is 0 when your html file containing the script is opened in the browser via the file scheme.当包含脚本的 html 文件通过文件方案在浏览器中打开时,状态为 0。 Make sure to place the files in your server (apache or tomcat whatever) and then open it via http protocol in the browser.确保将文件放在您的服务器(apache 或 tomcat 等)中,然后在浏览器中通过 http 协议打开它。 (ie http://localhost/myfile.html ) This is the solution. (即http://localhost/myfile.html )这是解决方案。

The cause of your problems is that you are trying to do a cross-domain call and it fails .您的问题的原因是您正在尝试进行跨域调用并且失败了

If you're doing localhost development you can make cross-domain calls - I do it all the time.如果您正在进行本地主机开发,您可以进行跨域调用 - 我一直都在这样做。

For Firefox, you have to enable it in your config settings对于 Firefox,您必须在配置设置中启用它

signed.applets.codebase_principal_support = true

Then add something like this to your XHR open code:然后将这样的内容添加到您的 XHR 打开代码中:

  if (isLocalHost()){
    if (typeof(netscape) != 'undefined' && typeof(netscape.security) != 'undefined'){
      netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
    }
  }

For IE, if I remember right, all you have to do is enable the browser's Security setting under "Miscellaneous → Access data sources across domains" to get it to work with ActiveX XHRs.对于 IE,如果我没记错的话,您所要做的就是在“杂项 → 跨域访问数据源”下启用浏览器的安全设置,以使其与 ActiveX XHR 一起使用。

IE8 and above also added cross-domain capabilities to the native XmlHttpRequest objects, but I haven't played with those yet. IE8 及更高版本还为原生 XmlHttpRequest 对象添加了跨域功能,但我还没有玩过这些功能。

实际上确保您的按钮类型是按钮不是提交,这导致了我最近遇到的状态冲突。

If the server responds to an OPTIONS method and to GET and POST (whichever of them you're using) with a header like:如果服务器响应 OPTIONS 方法以及 GET 和 POST(无论您使用的是哪个),并带有如下标题:

Access-Control-Allow-Origin: *

It might work OK.它可能工作正常。 Seems to in FireFox 3.5 and rekonq 0.4.0.似乎在 FireFox 3.5 和 rekonq 0.4.0 中。 Apparently, with that header and the initial response to OPTIONS, the server is saying to the browser, "Go ahead and let this cross-domain request go through."显然,使用该标头和对 OPTIONS 的初始响应,服务器对浏览器说:“继续,让这个跨域请求通过。”

Consider also the request timeout :还要考虑请求超时

Modern browser return readyState=4 and s tatus=0 if too much time passes before the server response.如果在服务器响应之前经过了太多时间,现代浏览器将返回readyState=4和 s tatus=0

setRequestHeader("Access-Control-Allow-Origin","*")到您的服务器响应中。

Open javascript console .打开javascript 控制台 You'll see an error message there.您会在那里看到一条错误消息。 In my case it was CORS.就我而言,它是 CORS。

I had faced a similar problem.我遇到过类似的问题。 Every thing was okay, the "readystate" was 4, but the "status" was 0. It was because I was using a Apache PHP portable server and my file in which I used the "XMLHttpRequest" object was a html file.一切正常,“就绪状态”为 4,但“状态”为 0。这是因为我使用的是 Apache PHP 便携式服务器,而我使用“XMLHttpRequest”对象的文件是一个 html 文件。 I changed the file extension to php and the problem was solved.我把文件扩展名改成php,问题就解决了。

要回答为什么http://127.0.0.1/cd_catalog.xml有效而http://localhost/cd_catalog.xml无效的问题:Firefox 将 127.0.0.1 和 localhost 视为两个不同的域。

To see what the problem is, when you get the cryptic error 0 go to ... |要查看问题是什么,当您收到神秘错误 0 时,请转到 ... | More Tools |更多工具 | Developer Tools (Ctrl+Shift+I) in Chrome (on the page giving the error) Chrome 中的开发人员工具 (Ctrl+Shift+I)(在给出错误的页面上)

Read the red text in the log to get the true error message.阅读日志中的红色文本以获取真正的错误消息。 If there is too much in there, right-click and Clear Console, then do your last request again.如果那里有太多,请右键单击并清除控制台,然后再次执行上次请求。

My first problem was, I was passing in Authorization headers to my own cross-domain web service for the browser for the first time.我的第一个问题是,我第一次将 Authorization 标头传递给我自己的浏览器跨域 Web 服务。

I already had:我已经有了:

Access-Control-Allow-Origin: *

But not:但不是:

Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization

in the response header of my web service.在我的 Web 服务的响应标头中。

After I added that, my error zero was gone from my own web server, as well as when running the index.html file locally without a web server, but was still giving errors in code pen.添加后,我自己的 Web 服务器以及在没有 Web 服务器的情况下在本地运行 index.html 文件时,我的错误零消失了,但仍然在代码笔中出现错误。

Back to ... |回到... | More Tools |更多工具 | Developer Tools while getting the error in codepen, and there is clearly explained: codepen uses https, so I cannot make calls to http, as the security is lower.开发者工具同时在codepen中得到错误,并且有明确的解释:codepen使用https,所以我无法调用http,因为安全性较低。

I need to therefore host my web service on https.因此,我需要在 https 上托管我的 Web 服务。

Knowing how to get the true error message - priceless!知道如何获得真正的错误信息 - 无价!

Here's another case in which status === 0 , specific to uploading:这是status === 0的另一种情况,特定于上传:

If you attach a 'load' event handler to XHR.upload , as suggested by MDN (scroll down to the upload part of 'Monitoring progress'), the XHR object will have status=0 and all the other properties will be empty strings.如果按照MDN 的建议(向下滚动到“监控进度”的上传部分)将'load'事件处理程序附加到XHR.upload ,则 XHR 对象将具有status=0并且所有其他属性将为空字符串。 If you attach the 'load' handler directly to the XHR object, as you would when downloading content, you should be fine (given you're not running off localhost).如果您将'load'处理程序直接附加到 XHR 对象,就像下载内容时一样,您应该没问题(假设您没有运行本地主机)。

However, if you want to get good data in your 'progress' event handlers, you need to attach a handler to XHR.upload , not directly to the XHR object itself.但是,如果您想在'progress'事件处理程序中获得好的数据,您需要将处理程序附加到XHR.upload而不是直接附加到 XHR 对象本身。

I've only tested this so far on Chrome OSX, so I'm not sure how much of the problem here is MDN's documentation and how much is Chrome's implementation...到目前为止我只在 Chrome OSX 上测试过这个,所以我不确定这里有多少问题是 MDN 的文档以及 Chrome 的实现有多少......

Alex Robinson already (and first) gives the correct answer to this issue. Alex Robinson 已经(并且首先)给出了这个问题的正确答案。 But to elaborate it a little more...但要详细说明一下......

You must add the HTTP response header:您必须添加 HTTP 响应标头:

Access-Control-Allow-Origin: *

If you do this, the result is not just 'might work', but 'will work'.如果你这样做,结果不仅仅是“可能有效”,而是“会有效”。

NB What you need to add is an HTTP response header - so you can only do this on a server which you control.注意您需要添加的是 HTTP响应标头 - 因此您只能在您控制的服务器上执行此操作。 It will never be possible to directly fetch http://w3schools.com/XML/cd_catalog.xml from its original URL using an XMLHttpRequest (as per OP's question), because that resource does not (at least, not as of 24 Apr 2015) include any such CORS header.永远不可能使用XMLHttpRequest (根据 OP 的问题)从其原始 URL 直接获取http://w3schools.com/XML/cd_catalog.xml ,因为该资源没有(至少,截至 2015 年 4 月 24 日) ) 包括任何此类 CORS 标头。

http://en.wikipedia.org/wiki/Cross-origin_resource_sharing gives more info. http://en.wikipedia.org/wiki/Cross-origin_resource_sharing提供了更多信息。

My problem similar to this was solved by checking my html code.我的类似问题是通过检查我的 html 代码解决的。 I was having an onclick handler in my form submit button to a method.我的表单提交按钮中有一个onclick处理程序到一个方法。 like this : onclick="sendFalconRequestWithHeaders()" .像这样: onclick="sendFalconRequestWithHeaders()" This method in turn calls ajax just like yours, and does what I want.这个方法反过来像你一样调用ajax,并且做我想要的。 But not as expected, my browser was returning nothing.但不像预期的那样,我的浏览器没有返回任何内容。

Learned From someone's hardwork , I have returned false in this handler, and solved.某人的努力中学到,我在这个处理程序中返回了 false,并解决了。 Let me mention that before arriving to this post, I have spent a whole 3-day weekend and a half day in office writing code implementing CORS filters , jetty config , other jersey and embedded jetty related stuff - just to fix this., revolving all my understanding around cross domain ajax requests and standards stuff.让我提一下,在到达这篇文章之前,我花了整整 3 天半的周末时间在办公室编写代码,实现CORS filtersjetty config 、其他jersey and embedded jetty相关的东西——只是为了解决这个问题。,旋转所有我对cross domain ajax requests和标准的理解。 It was ridiculous how simple mistakes in javascript make you dumb. javascript 中的简单错误让你变得愚蠢,这太荒谬了。

To be true, I have tried signed.applets.codebase_principal_support = true and written isLocalHost() **if** .确实,我已经尝试过signed.applets.codebase_principal_support = true并编写了isLocalHost() **if** may be this method needs to be implemented by us, firefox says there is no such Now I have to clean my code to submit git patch cleanly.可能是这个方法需要我们自己实现,firefox说没有这个现在我要清理我的代码才能干净地提交git补丁。 Thanks to that someone.感谢那个人。

A browser request "127.0.0.1/somefile.html" arrives unchanged to the local webserver, while "localhost/somefile.html" may arrive as "0:0:0:0:0:0:0:1/somefile.html" if IPv6 is supported.浏览器请求“127.0.0.1/somefile.html”未更改地到达本地网络服务器,而“localhost/somefile.html”可能以“0:0:0:0:0:0:0:1/somefile.html”的形式到达" 如果支持 IPv6。 So the latter can be processed as going from a domain to another.所以后者可以被处理为从一个域到另一个域。

Alex Robinson and bmju provided valuable information to understand cross-origin issues. Alex Robinson 和 bmju 提供了宝贵的信息来理解跨域问题。 I wanted to add that you may need to make an explicit OPTIONS call in your client code before making the desired GET/POST (eg against a CORS OAuth service endpoint).我想补充一点,在进行所需的 GET/POST(例如针对 CORS OAuth 服务端点)之前,您可能需要在客户端代码中进行显式 OPTIONS 调用。 Your browser/library may not automatically handle the OPTIONS request.您的浏览器/库可能不会自动处理 OPTIONS 请求。 Gruber, this is one of the possible answers to your question. Gruber,这是您问题的可能答案之一。

I had the same problem (readyState was 4 and status 0) , then I followed a different approach explained in this tutorial: https://spring.io/guides/gs/consuming-rest-jquery/我遇到了同样的问题(readyState 为 4,状态为 0) ,然后我采用了本教程中解释的不同方法: https : //spring.io/guides/gs/sumption-rest-jquery/

He didn't use XMLHttpRequest at all, instead he used jquery $.ajax() method:他根本没有使用XMLHttpRequest ,而是使用了jquery $.ajax()方法:

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="hello.js"></script>
</head>

<body>
    <div>
        <p class="greeting-id">The ID is </p>
        <p class="greeting-content">The content is </p>
    </div>
</body>

and for the public/hello.js file (or you could insert it in the same HTML code directly):对于 public/hello.js 文件(或者您可以直接将其插入到相同的 HTML 代码中):

$(document).ready(function() 
 {
    $.ajax({
        url: "http://rest-service.guides.spring.io/greeting"
   }).then(function(data) {
      $('.greeting-id').append(data.id);
      $('.greeting-content').append(data.content);
   });
 });

我不得不将我当前的 IP 地址(再次)添加到Atlas MongoDB 白名单,因此摆脱了 XMLHttpRequest status 0 错误

bottle app in python: python中的瓶子应用程序:

@route('/mazer2/get', method='POST')
def GetMaze2():
    if MazeCore == None: abort(666, "MazeCore поломался :///")
    Check()
    Comm = request.body.read().decode("utf-8")
    Map = MazeCore.GetMaze2(Comm, TestToken2())
    response.headers["Access-Control-Allow-Origin"] = "*" #Here ;'-} It helped me
    return Map

I had the same problem when I tried to consume some web methods created by python in a flask environment, by XMLHttpRequest.当我尝试使用 XMLHttpRequest 在烧瓶环境中使用 python 创建的一些 Web 方法时,我遇到了同样的问题。 After inspecting the firefox console, I realised that the cause of problem was Same Origin Policy, which prevents calling web methods of a different ORIGIN (An Origin consists of a 3 part tuple including: protocol, domain, and port number).在检查 firefox 控制台后,我意识到问题的原因是同源策略,它阻止调用不同ORIGIN 的Web 方法(一个 Origin 由 3 部分元组组成,包括:协议、域和端口号)。 For me, the solution was to use CORS , and fortunately there is a python package named flask-cors which I used and everything works fine.对我来说,解决方案是使用CORS ,幸运的是我使用了一个名为flask-cors的 python 包,一切正常。

我刚刚遇到这个问题,因为我使用0.0.0.0作为我的服务器,将其更改为localhost并且它可以工作。

setRequestHeader("Access-Control-Allow-Origin","*") 在您的清单中

Edit: Please read Malvolio's comments below as this answer's knowledge is outdated.编辑:请阅读下面 Malvolio 的评论,因为此答案的知识已过时。

You cannot do cross-domain XMLHttpRequests.您不能执行跨域 XMLHttpRequests。

The call to 127.0.0.1 works because your test page is located at 127.0.0.1 , and the local test also works since, well... it's a local test.127.0.0.1的调用有效,因为您的测试页面位于127.0.0.1 ,并且本地测试也有效,因为……这是本地测试。

The other two tests fail because JavaScript cannot communicate with a distant server through XMLHttpRequest.其他两个测试失败是因为 JavaScript 无法通过 XMLHttpRequest 与远程服务器通信。

You might instead consider either:你可以考虑:

  • XMLHttp-request your own server to fetch your remote XML content for you (php script, for example) XMLHttp-请求您自己的服务器为您获取远程 XML 内容(例如 php 脚本)
  • Trying to use a service like GoogleAppEngine if you want to keep it full JavaScript.如果您想保持完整的 JavaScript,请尝试使用像 GoogleAppEngine 这样的服务。

Hope that helps希望有帮助

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

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