我在XMLHttpRequest中缺少什么? [英] What am I missing in the XMLHttpRequest?

查看:105
本文介绍了我在XMLHttpRequest中缺少什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是javascript和ajax世界的新手,但是想要学习。

I'm completely new to the javascript and ajax world but trying to learn.

现在我正在测试XMLHttpRequest,我甚至无法工作最简单的例子。这是我正在尝试运行的代码

Right now I'm testing the XMLHttpRequest and I can't make work even the simplest example. This is the code I'm trying to run

    <script type="text/javascript">
        function test() {
            xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200){
                    var container = document.getElementById('line');
                    container.innerHTML = xhr.responseText;
                } else {
                    alert(xhr.status);
                }
            }  

            xhr.open('GET', 'http://www.google.com', true);                  
            xhr.send(null); 
        }
    </script>

我总是得到状态为0的警报。我已经阅读了大量有关此问题的网页我不知道我错过了什么。感谢任何帮助,谢谢!

And I always get the alert with the status 0. I've read tons of webs about this and I don't know what am I missing. I will appreciate any help, thanks!

推荐答案

您正在遇到同源政策

除非您的代码实际上在www.google.com上运行(这不太可能),否则会出错。

Unless your code is actually running on www.google.com (which is unlikely), this is going to error.

另外,虽然目前这不会给你造成问题,但这种做法很糟糕,并且会导致竞争条件,你在整个地方使用全局变量。

Also, and while this isn't causing you a problem at the moment, it is poor practice and can lead to race conditions, you are using globals all over the place.

将xhr变量设为函数的本地变量

Make the xhr variable local to the function

var xhr = new XMLHttpRequest();

并在中引用它 onreadstatechange 方法。

if (this.readyState == 4 && this.status == 200){
// etc etc

这篇关于我在XMLHttpRequest中缺少什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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