XMLHttpRequest.status总是返回0 [英] XMLHttpRequest.status always returning 0

查看:230
本文介绍了XMLHttpRequest.status总是返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

html

 < a href =#onclick =MyObj.startup()>点击我< / A> 



js code

  var MyObj = 
{
startup:function()
{
var ajax = null;
ajax = new XMLHttpRequest();
ajax.open('GET','http://www.nasa.gov',true);
ajax.onreadystatechange = function(evt)
{
if(ajax.readyState == 4)
{
if(ajax.status == 200)
{
window.dump(:) \\\
);



window.dump(:( \\\
);
}
}
}
ajax.send(null);
}
}

ajax.status 总是返回0,不管是哪一个站点,不管是什么实际的返回码,我说实际的,因为 ajax.statusText 返回正确的值,例如OK或Redirecting ...
$ b $ p $ ajax.readyState 也返回正确的值在本地环境中,你可以通过设置一个php代理服务器(xampp a server)轻松解决这个问题。

并传递一个查询字符串为你想抓取的网址)。让你的PHP代理wget的网址,并呼应其内容。这样你的本地HTML文件(当作为 http://localhost/your.html )可以通过doma发送ajax请求整天,只要不要期望内容工作,就好像它在本地域。


html

<a href="#" onclick="MyObj.startup()">click me</a>

js code

var MyObj = 
{
    startup : function()
    {
        var ajax = null;
        ajax = new XMLHttpRequest();
        ajax.open('GET', 'http://www.nasa.gov', true);
        ajax.onreadystatechange = function(evt)
        {
            if(ajax.readyState == 4)
            {
                if (ajax.status == 200)
                {
                    window.dump(":)\n");
                }
                else
                {
                    window.dump(":(\n");
                }
            }
        }
        ajax.send(null);
    }
}

ajax.status always returning 0, no matter which site it is, no matter what is the actual return code. I say actual, because ajax.statusText returning correct value, eg OK or Redirecting...

ajax.readyState also returns proper values and 4 at the end.

解决方案

You can overcome this easily in a local environment by setting up a php proxy (xampp a server and pass a querystring for the url you want to grab). Have your php proxy wget the url and echo its contents. That way your local html file (when viewed as http://localhost/your.html) can send ajax requests out of domain all day. Just don't expect the content to work as though it were local to that domain.

这篇关于XMLHttpRequest.status总是返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆