2012-07-05 69 views
2

就像在标题中一样,我的问题是,是否可以判断XMLhttpRequest的打开和发送方法是否真正起作用?有没有任何指标? 示例代码:XMLHttpRequest打开并发送:如何判断它是否有效

cli = new XMLHttpRequest(); 
cli.open('GET', 'http://example.org/products'); 
cli.send(); 

我试图代码故障处理这个,但我需要能够告诉我们,如果请求失败,这样我就可以处理它。

+2

是。它是。 **已经咨询了解释如何使用XHR的在线资源/文档? -1 **;阅读一些,然后,如果还有其他不清楚的要点,请提出一个更直接的问题。 (我会推荐使用XHR包装器,但它是一样的想法。) – 2012-07-05 20:05:11

+0

@pst在我看来,操作的异步性质可能合法地难以被一个新手所理解,因为这个人可能会被阻止。这就是我回答的原因。你认为我不应该这样做吗? – 2012-07-05 20:22:56

+0

@dystroy除了这个事实,这是一个很好的例子* ..人们编写文档/教程是有原因的。 – 2012-07-05 20:25:56

回答

3

这是一个异步操作。您的脚本在发送请求时继续执行。

您使用检测回调状态的变化:

var cli = new XMLHttpRequest(); 
cli.onreadystatechange = function() { 
     if (cli.readyState === 4) { 
      if (cli.status === 200) { 
         // OK 
         alert('response:'+cli.responseText); 
         // here you can use the result (cli.responseText) 
      } else { 
         // not OK 
         alert('failure!'); 
      } 
     } 
}; 
cli.open('GET', 'http://example.org/products'); 
cli.send(); 
// note that you can't use the result just here due to the asynchronous nature of the request 
+0

适合我。谢谢。 – 2014-11-06 21:51:47

-1
req = new XMLHttpRequest; 
req.onreadystatechange = dataLoaded; 
req.open("GET","newJson2.json",true); 
req.send(); 

function dataLoaded() 
{ 
    if(this.readyState==4 && this.status==200) 
    { 
     // success 
    } 
    else 
    { 
     // io error 
    } 
} 
相关问题