javascript XDomainRequest 与 XMLHTTPRequest
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25141650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XDomainRequest vs XMLHTTPRequest
提问by Mowday
We are creating an application using PixiJS which has a dynamic json loader in it.
我们正在使用 PixiJS 创建一个应用程序,其中包含一个动态 json 加载器。
It loads the .json files using the following:
它使用以下内容加载 .json 文件:
if(window.XDomainRequest)
{
this.ajaxRequest = new window.XDomainRequest();
}
else if (window.XMLHttpRequest)
{
this.ajaxRequest = new window.XMLHttpRequest();
}
else
{
this.ajaxRequest = new window.ActiveXObject('Microsoft.XMLHTTP');
}
Which seems to work everywhere except on windows phone and IE. However, if I swap XMLHttpRequest with XDomainRequest it works fine.
除了在 Windows 手机和 IE 上,它似乎在任何地方都可以使用。但是,如果我将 XMLHttpRequest 与 XDomainRequest 交换它工作正常。
So finally, can someone please explain the differences between XDomainRequest and XMLHTTPRequest? Which one should take precedence over the other?
最后,有人可以解释一下 XDomainRequest 和 XMLHTTPRequest 之间的区别吗?哪一个应该优先于另一个?
回答by MrCode
XDomainRequest is the only way of having an XHR that supports CORSin IE8 and 9. At the time of IE8, Microsoft decided to come up with their own CORS XHR instead of the standard CORS XMLHttpRequest which is now used in IE10. Since IE10, XDomainRequest has been removed (editor: see comment).
XDomainRequest 是在 IE8 和 9中拥有支持CORS的唯一方法。在 IE8 的时候,微软决定提出自己的 CORS XHR,而不是现在在 IE10 中使用的标准 CORS XMLHttpRequest。从 IE10 开始,XDomainRequest 已被删除(编辑:见评论)。
You should only use XDomainRequest if you need CORS in IE8/9. XDomainRequest is not completely interchangeable with XMLHttpRequest, the interfaces aren't exactly the same. One is example is it doesn't support the onreadystatechange
event. So if you want to switch between them like in the question, you will need to make sure you use onload
not onreadystatechange
and check any other functionality is interchangeable.
如果您在 IE8/9 中需要 CORS,您应该只使用 XDomainRequest。XDomainRequest 与 XMLHttpRequest 不能完全互换,接口也不完全相同。一个例子是它不支持该onreadystatechange
事件。所以,如果你想在喜欢的问题在它们之间进行切换,你需要确保你使用onload
不onreadystatechange
检查任何其他功能是可以互换的。
There's an example usage in this answer.
这个答案中有一个示例用法。