XMLHttpRequest status 0 (responseText is empty)

Cannot get data with XMLHttpRequest (status 0 and responseText is empty):

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".

The same situation with the localhost request (cd_catalog.xml is saved as a local file)

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

But with the localhost IP request

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)

What can cause the problem (status=0) with the online request?

PS: Live HTTP Headers shows that everything is OK in all 4 cases:

  HTTP/1.1 200 OK
  Content-Length: 4742

PS2: Apache local web server on VMWare (host OS Win7, Guest OS Ubuntu, Network adapter – NAT). Browser – Firefox.


状态为0,当你的HTML文件包含脚本在浏览器中通过文件协议打开时。请务必将文件放在你的服务器(apache或tomcat)中,然后在浏览器中通过http协议打开它(例如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

signed.applets.codebase_principal_support = true

Then add something like this to your XHR open code:

  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.

IE8 and above also added cross-domain capabilities to the native XmlHttpRequest objects, but I haven't played with those yet.

链接地址: http://www.djcxy.com/p/22322.html

上一篇: PHP和AJAX登录表单

下一篇: XMLHttpRequest状态0(responseText为空)