当前位置: 动力学知识库 > 问答 > 编程问答 >

ajax - Why IE9 (8) treat XDR differently with try/catch

问题描述:

So I want to do CORS in IE8,9, so I have to use XDomainRequest. So I created:

function post(url, data) {

var request = new XMLHttpRequest();

try {

request.open('POST', url, true);

request.setRequestHeader('Content-Type', 'text/plain');

} catch (err) {

if (err.message.indexOf('Access is denied') > -1) {

request = new XDomainRequest();

request.open('POST', url);

} else {

throw err;

}

}

request.send(JSON.stringify(data));

}

Which works fine. Then I come across this article. It suggested this:

function post(url, data) {

var request = new XMLHttpRequest();

if ('withCredentials' in request) {

request.open('POST', url, true);

request.setRequestHeader('Content-Type', 'text/plain');

} else if (typeof XDomainRequest !== 'undefined') {

console.log('here') // 'here' in IE8,9

request = new XDomainRequest();

request.open('POST', url);

} else {

throw new Error('XHR cannot handle CORS and XDR is not available');

}

request.send(JSON.stringify(data));

}

Which should also be fine. But when I look at the headers of the network, the try/catch solution gives me:

while the if ('withCredentials' in request):

They have different Content-Type: text/plain!! Someone know why?

网友答案:

In the else if (typeof XDomainRequest !== 'undefined') code block the content type is not set, Since you're using IE8/9 this block will be executed.

分享给朋友:
您可能感兴趣的文章:
随机阅读: