【发布时间】:2010-09-29 17:35:24
【问题描述】:
创建XMLHttpRequest 对象的最佳方法是什么?
它应该适用于所有支持的浏览器。
【问题讨论】:
标签: javascript ajax cross-browser xmlhttprequest
创建XMLHttpRequest 对象的最佳方法是什么?
它应该适用于所有支持的浏览器。
【问题讨论】:
标签: javascript ajax cross-browser xmlhttprequest
对于无库解决方案,您可以很容易地模拟 Prototype 对 Try.these 的使用:
function newAjax() {
try { return new XMLHttpRequest(); } catch(){}
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(){}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(){}
try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(){}
try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(){}
return false;
}
【讨论】:
这是一个有用的链接和一些代码(应该涵盖所有基础)
var request = null;
function InitAJAX()
{
var objxml = null;
var ProgID = ["Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.3.0", "Microsoft.XMLHTTP"];
try
{
objxml = new XMLHttpRequest();
}
catch(e)
{
for (var i = 0; i < ProgID.length; i++)
{
try
{
objxml = new ActiveXObject(ProgID[i]);
}
catch(e)
{
continue;
}
}
}
return objxml;
}
request = InitAJAX();
【讨论】:
使用jQuery(或类似的 JavaScript 库)。它负责处理诸如进行 Ajax 调用之类的跨浏览器兼容性问题。
For example,使用jQuery Ajax call:
$.ajax({
url: 'document.xml',
type: 'GET',
dataType: 'xml',
timeout: 1000,
error: function(){
alert('Error loading XML document');
},
success: function(xml){
// do something with xml
}
});
【讨论】:
我建议关注Sergey's advise 或自己为 IE 编写一个小而不太复杂的补丁:
if(typeof window.XMLHttpRequest === 'undefined' &&
typeof window.ActiveXObject === 'function') {
window.XMLHttpRequest = function() {
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
return new ActiveXObject('Microsoft.XMLHTTP');
};
}
那你就可以了
var req = new XMLHttpRequest;
即使在 IE 中。
编辑 2011-02-18: 请参阅 this blogpost,了解新选择 MSXML 版本背后的基本原理...
【讨论】:
这是我用的,对我来说很好用:
function request()
{
try
{
try
{
return new ActiveXObject("Microsoft.XMLHTTP")
}
catch( e )
{
return new ActiveXObject("Msxml2.XMLHTTP")
}
}
catch(e)
{
return new XMLHttpRequest()
}
}
【讨论】:
我同意 Cletus 对 jQuery 的建议,还查看了 jQuery Form 插件,它非常强大且易于使用,可以快速将您的表单转换为通过 Ajax 工作。
【讨论】:
函数 CreateXmlHttpObj() {
try {
XmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
XmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (oc) {
XmlHttpObj = null;
}
}
// if unable to create using IE specific code then try creating for Mozilla (FireFox)
if (!XmlHttpObj && typeof XMLHttpRequest != "undefined") {
XmlHttpObj = new XMLHttpRequest();
}
}
【讨论】: