以下代码段在IE7中无效吗?
var http = new XMLHttpRequest();
var url = 'http://my_site.com/';
var obj = createJsonParamsObj();
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(JSON.stringify(obj));
从文档中可以看出new XMLHttpRequest()
应该有效,但是由于我无法测试它(仅在兼容模式下)而有疑问,所以也许我最好使用new ActiveXObject
。
答案 0 :(得分:10)
谷歌中的小搜索将为您的基本问题提供一个很好的答案
/*
Provide the XMLHttpRequest constructor for Internet Explorer 5.x-6.x:
Other browsers (including Internet Explorer 7.x-9.x) do not redefine
XMLHttpRequest if it already exists.
This example is based on findings at:
http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
*/
if (typeof XMLHttpRequest === "undefined") {
XMLHttpRequest = function () {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
// Microsoft.XMLHTTP points to Msxml2.XMLHTTP and is redundant
throw new Error("This browser does not support XMLHttpRequest.");
};
}
或
/**
* Gets an XMLHttpRequest. For Internet Explorer 6, attempts to use MSXML 6.0,
* then falls back to MXSML 3.0.
* Returns null if the object could not be created.
* @return {XMLHttpRequest or equivalent ActiveXObject}
*/
function getXHR() {
if (window.XMLHttpRequest) {
// Chrome, Firefox, IE7+, Opera, Safari
return new XMLHttpRequest();
}
// IE6
try {
// The latest stable version. It has the best security, performance,
// reliability, and W3C conformance. Ships with Vista, and available
// with other OS's via downloads and updates.
return new ActiveXObject('MSXML2.XMLHTTP.6.0');
} catch (e) {
try {
// The fallback.
return new ActiveXObject('MSXML2.XMLHTTP.3.0');
} catch (e) {
alert('This browser is not AJAX enabled.');
return null;
}
}
}
参考:http://en.wikipedia.org/wiki/XMLHttpRequest和http://www.webmasterworld.com/javascript/4027629.htm
答案 1 :(得分:1)
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
最好在IE7中使用ActiveXObject
,如下所示:
new window.ActiveXObject("Microsoft.XMLHTTP")
答案 2 :(得分:0)
example from Microsoft几乎完全按照您的代码执行操作:
var oReq = new XMLHttpRequest();
oReq.open("POST", sURL, false);
oReq.setRequestHeader("Content-Type", "text/xml");
oReq.send(sRequestBody);
从这里开始,我甚至可以设想的唯一可能的失败点是支持application/x-www-form-urlencoded
的特定Content-Type
值的错误,我非常怀疑这是一个现存问题。< / p>
还要记住包含JSON库,因为IE7不包含本机JSON
对象。