我尝试发出跨域 POST 请求并取回 JSON 编码的响应,
除 IE 7、8、9 外,一切正常。我尝试了这些解决方案,但出现此错误:
对象不支持属性或方法“setRequestHeader”
函数 createXMLHTTPObject() - 尝试 1
function createXMLHTTPObject() {
var xmlhttp = false;
var is_IE = window.XDomainRequest ? true : false;
if (is_IE) {
xmlhttp = new window.XDomainRequest();
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlhttp;
}
函数 createXMLHTTPObject() - 尝试 2
var XMLHttpFactories = [
function() { return new XMLHttpRequest() },
function() { return new ActiveXObject("Msxml2.XMLHTTP") },
function() { return new ActiveXObject("Msxml3.XMLHTTP") },
function() { return new ActiveXObject("Microsoft.XMLHTTP") }
];
function createXMLHTTPObject() {
var xmlhttp = false;
for (var i=0; i<XMLHttpFactories.length; i++) {
try {
xmlhttp = XMLHttpFactories[i]();
}
catch(e) {
continue;
}
break;
}
return xmlhttp;
}
函数 send()
在这里它返回错误,在:req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
function send(postData, callback) {
var url = 'http://domain.com/ajax-processing.php'; //url overlap
var req = createXMLHTTPObject();
if (!req) return;
var method = (postData) ? "POST" : "GET";
req.open(method, url, true);
req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
if (postData) {
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
req.onreadystatechange = function() {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
console.log('HTTP error ' + req.status);
return;
}
callback(req);
}
if (req.readyState == 4) return;
req.send(postData);
}
这里我调用发送函数
var insert = 'id=1&type=insert';
CLib.send(insert, function(data) {
console.log(data);
});
是否可以在 IE 中进行跨域请求?
我怎样才能在不使用任何其他库(如 jQuery)的情况下留下这部分?