热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

XMLHttpRequest异步不起作用,总是返回状态0-XMLHttpRequestasynchronousnotworking,alwaysreturnsstatus0

HeresasampleXMLHttpRequestIcobbledtogetherfromw3schools下面是我从w3schools收集的XMLHttpRequest示例

Here's a sample XMLHttpRequest I cobbled together from w3schools

下面是我从w3schools收集的XMLHttpRequest示例







Using the XMLHttpRequest object

XMLHttpRequest always returns a zero status.

XMLHttpRequest总是返回零状态。

Nothing shows up in Firefox's error console.

Firefox的错误控制台什么都没有显示。

If I change the request to synchronous one by changing the line

如果我通过更改行将请求更改为同步请求

xmlhttp.open("GET","SBL_PROBES.htm",true);

to

xmlhttp.open("GET","SBL_PROBES.htm",false);

and un-comment the line

和取消一行的注释

//T = xmlhttp.responseText;

The text of the requested file is returned.

返回所请求文件的文本。

The HTM and the file reside in the same directory. If you try this you will need a file SBL_PROBES.htm there also, it's contents are irrelevant.

HTM和文件位于同一个目录中。如果您尝试这样做,您将需要一个文件SBL_PROBES。htm,它的内容是无关的。

I'm using Firefox 3.6.22.

我使用Firefox 3.6.22。

Could this be a cross domain problem? If so, why does it work as a synchronous request?

这是一个跨域问题吗?如果是,为什么它作为一个同步请求工作?

5 个解决方案

#1


15  

You can use a function inside the if statement. This function is executed when readystate changes to 4.

可以在if语句中使用函数。当readystate更改为4时,将执行此函数。

var handleRespOnse= function (status, response) {
   alert(response)
}
var handleStateChange = function () {
   switch (xmlhttp.readyState) {
      case 0 : // UNINITIALIZED
      case 1 : // LOADING
      case 2 : // LOADED
      case 3 : // INTERACTIVE
      break;
      case 4 : // COMPLETED
      handleResponse(xmlhttp.status, xmlhttp.responseText);
      break;
      default: alert("error");
   }
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.Onreadystatechange=handleStateChange;
xmlhttp.open("GET","SBL_PROBES.htm",true);
xmlhttp.send(null);

Your old code did a asynchronous call and continued just with the alert Statement. T was empty at this time.

您的旧代码执行了一个异步调用,并继续使用alert语句。这时T是空的。

Ok, I'll explain a little bit how this whole thing works:

好吧,我来解释一下整个过程:

First we define two callback functions, which we call later in the request, named handleResponse and handleStateChange.

首先,我们定义两个回调函数,稍后在请求中调用它们,名为handleResponse和handleStateChange。

Afterwards we create a Object, which represents the XMLHttpRequest

然后我们创建一个对象,它表示XMLHttpRequest

var xmlhttp=new XMLHttpRequest();

This results in an Object as follows (simplyfied):

这就产生了如下的对象(简单化):

XMLHttpRequest { status=0, readyState=0, multipart=false, Onreadystatechange=handleEvent()}

With the open(...) function call you set parameters for the request:

使用open(…)函数调用您为请求设置参数:

xmlhttp.open("GET","SBL_PROBES.htm",true);

This means, do a asynchronous GET Request to fetch the Page SBL_PROBES.htm Then the send(...) function is called which fires the request itself.

这意味着,执行一个异步GET请求来获取SBL_PROBES页面。然后调用send(…)函数来触发请求本身。

We registered a callback function for the onreadystatechange, as you can imagine, this is actually an eventHandler. Each time the state changes this function is called. (It is the same as if you register a callback function to an onKeyUp Event in a form, this callback is triggered each time your key goes up :) )

我们为onreadystatechange注册了一个回调函数,可以想象,这实际上是一个eventHandler。每当状态改变时,就调用这个函数。(这与在表单中向onKeyUp事件注册回调函数是一样的,这个回调会在每次您的键上升时触发:)

The only case which is of interest for your problem is state 4. Therefor the handleRequest callback function is called only in state 4. At this time you Request has actually a result, and further a status. (Status means your webserver returned a status code 200=ok, 404=not found etc.)

唯一对你的问题感兴趣的情况是状态4。因此handleRequest回调函数只在状态4中调用。此时,您的请求实际上具有一个结果,并进一步具有一个状态。(状态意味着您的web服务器返回一个状态码200=ok, 404=not found等)

That is not all the magic which is behind the ajax stuff, but should give you a simplified overview, what is actually happening behind the scenes. It is important that you test this on a webserver, do not use file:// for testing.

这并不是ajax背后的所有神奇之处,但应该给您一个简单的概述,即幕后发生的实际情况。在webserver上测试这一点很重要,不要使用file://用于测试。

If you need more in detail info, just let me know.

如果你需要更多的细节信息,请告诉我。

#2


8  

Status Zero happens for two reasons.

状态零发生有两个原因。

  1. You are running off the file protocol.
  2. 您正在运行文件协议。
  3. Something is posting back the page when the Ajax request is active.
  4. 当Ajax请求处于活动状态时,会有一些东西回传给页面。

I believe you are seeing #2 here. SO you need to cancel the button click.

我相信你在这里看到的是第二条。所以你需要取消按钮点击。


In your code above that alert(T) will always say nothing when the request is asynchronous.

在您上面的代码中,当请求是异步的时候,该警报(T)将始终保持沉默。

#3


3  

Its because async returns before the request returns. Synchronous requests return after the request returns.

因为异步在请求返回之前返回。在请求返回后返回同步请求。

Try manipulating your logic in here.

试着在这里操作你的逻辑。

xmlhttp.Onreadystatechange=function()
  {
    alert ("rdystate: " + xmlhttp.readyState);
    alert ("status: "   + xmlhttp.status);
    alert ("Text: "     + xmlhttp.statusText);
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      T = xmlhttp.responseText;
      alert(T);
    }
  }

#4


1  

I've battled the problem of not getting a result when using asynchronous XMLHttpRequest open statement. Since this question is the first I found when using google, here is how I solved it:

我曾遇到过使用异步XMLHttpRequest open语句时得不到结果的问题。由于这个问题是我在使用谷歌时发现的第一个问题,下面是我如何解决它的:

If you use a button that is inside a form, make sure it is set to type="submit" and Onclick="return myFunction()". And in myFunction(), make sure you return false, not true! By returning true from the function, you reload the page and the XML object disappears. If you return false, the XML request gets the time it needs to complete and the onreadystatechange function will be run.

如果使用表单内部的按钮,请确保将其设置为type="submit"和Onclick="return myFunction()"。在myFunction()中,确保返回false,而不是true!通过从函数返回true,重新加载页面,XML对象就消失了。如果返回false,则XML请求获得完成所需的时间,并运行onreadystatechange函数。

Source: Flask Mailing List

来源:烧瓶邮件列表

#5


0  

I have now received the good response to this common problem. The response follow:

我现在已经收到了对这个普遍问题的良好回应。响应:

This is a very common problem when developing for the web. There's two ways around it.

在为web开发时,这是一个非常常见的问题。有两种方法。

  1. The first is to use JSONP, which our API supports when you add a query parameter ("?callback=foo"). This should get you up and running right away and is great for development, but it isn't secure for production use since users get access to your API key.
  2. 第一个是使用JSONP,当您添加一个查询参数(“?callback=foo”)时,我们的API支持它。这应该可以让您立即启动并运行,并且对开发很有帮助,但是对于生产使用来说并不安全,因为用户可以访问您的API密钥。
  3. The second (which is what we use on Forecast, and is the best method for production) is to set up a proxy server on your own domain which can make requests to Forecast on the user's behalf. This sidesteps the browser's same-origin policy, prevents users from accessing your API key (which can be stored server-side), and also allows you to make use of request caching, if desired. (Our favorite web server, NGINX, supports this out of the box and is really easy to configure. If you need some sample configurations, let us know!)
  4. 第二种(这是我们在Forecast中使用的,也是最好的生产方法)是在您自己的域中设置一个代理服务器,该服务器可以代表用户发出预测请求。这绕过了浏览器的同源策略,防止用户访问您的API密钥(可以存储在服务器端),并允许您使用请求缓存(如果需要的话)。(我们最喜欢的web服务器NGINX支持开箱即用,并且非常容易配置。如果您需要一些示例配置,请告诉我们!)

推荐阅读
  • Hibernate延迟加载深入分析-集合属性的延迟加载策略
    本文深入分析了Hibernate延迟加载的机制,特别是集合属性的延迟加载策略。通过延迟加载,可以降低系统的内存开销,提高Hibernate的运行性能。对于集合属性,推荐使用延迟加载策略,即在系统需要使用集合属性时才从数据库装载关联的数据,避免一次加载所有集合属性导致性能下降。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 程序员如何选择机械键盘轴体?红轴和茶轴对比
    本文介绍了程序员如何选择机械键盘轴体,特别是红轴和茶轴的对比。同时还介绍了U盘安装Linux镜像的步骤,以及在Linux系统中安装软件的命令行操作。此外,还介绍了nodejs和npm的安装方法,以及在VSCode中安装和配置常用插件的方法。最后,还介绍了如何在GitHub上配置SSH密钥和git的基本配置。 ... [详细]
  • Ihaveaforminadirectivetemplate:我在指令模板中有一个表单:<formn ... [详细]
  • 我有一个带有H2数据库的springboot应用程序。该应用程序会在启动时引导数据库,为此,我在 ... [详细]
  • Spring MVC定制用户登录注销实现示例
    这篇文章描述了如何实现对SpringMVCWeb应用程序的自定义用户访问(登录注销)。作为前提,建议读者阅读这篇文章,其中介 ... [详细]
  • Linux重启网络命令实例及关机和重启示例教程
    本文介绍了Linux系统中重启网络命令的实例,以及使用不同方式关机和重启系统的示例教程。包括使用图形界面和控制台访问系统的方法,以及使用shutdown命令进行系统关机和重启的句法和用法。 ... [详细]
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
  • MyBatis多表查询与动态SQL使用
    本文介绍了MyBatis多表查询与动态SQL的使用方法,包括一对一查询和一对多查询。同时还介绍了动态SQL的使用,包括if标签、trim标签、where标签、set标签和foreach标签的用法。文章还提供了相关的配置信息和示例代码。 ... [详细]
  • 本文介绍了使用cacti监控mssql 2005运行资源情况的操作步骤,包括安装必要的工具和驱动,测试mssql的连接,配置监控脚本等。通过php连接mssql来获取SQL 2005性能计算器的值,实现对mssql的监控。详细的操作步骤和代码请参考附件。 ... [详细]
  • IjustinheritedsomewebpageswhichusesMooTools.IneverusedMooTools.NowIneedtoaddsomef ... [详细]
  • iOS超签签名服务器搭建及其优劣势
    本文介绍了搭建iOS超签签名服务器的原因和优势,包括不掉签、用户可以直接安装不需要信任、体验好等。同时也提到了超签的劣势,即一个证书只能安装100个,成本较高。文章还详细介绍了超签的实现原理,包括用户请求服务器安装mobileconfig文件、服务器调用苹果接口添加udid等步骤。最后,还提到了生成mobileconfig文件和导出AppleWorldwideDeveloperRelationsCertificationAuthority证书的方法。 ... [详细]
  • Javascript中带有加号 - 减号(±)的极坐标曲线方程 - Polar curve equation with plus-minus sign (±) in Javascript
    IamtryingtodrawpolarcurvesonHTMLcanvasusingJavascript.WhatshouldIdowhenIwanttoco ... [详细]
  • PHP引用的概念和用法详解
    本文详细介绍了PHP中引用的概念和用法。引用是指不同的变量名访问同一个变量内容,类似于Unix文件系统中的hardlink。文章从引用的定义、作用、语法和注意事项等方面进行了解释和示例。同时还介绍了对未定义变量使用引用的情况,以及在函数和new运算符中使用引用的注意事项。 ... [详细]
  • 本文讨论了在使用Git进行版本控制时,如何提供类似CVS中自动增加版本号的功能。作者介绍了Git中的其他版本表示方式,如git describe命令,并提供了使用这些表示方式来确定文件更新情况的示例。此外,文章还介绍了启用$Id:$功能的方法,并讨论了一些开发者在使用Git时的需求和使用场景。 ... [详细]
author-avatar
柳辰光
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有