使用javascript的跨服务器请求
下面的脚本在我通过IE运行时有效,但在我通过Chrome或Firefox运行时无效。我得到“发生调用错误”。有人知道为什么会发生这种情况吗?我需要做些什么来修复它使用javascript的跨服务器请求,javascript,cors,Javascript,Cors,下面的脚本在我通过IE运行时有效,但在我通过Chrome或Firefox运行时无效。我得到“发生调用错误”。有人知道为什么会发生这种情况吗?我需要做些什么来修复它 var isIE8 = window.XDomainRequest ? true : false; var dictionary = createCrossDomainRequest(); var url = 'http://www.math.sjsu.edu/~foster/dictionary.txt'; makeRequest(
var isIE8 = window.XDomainRequest ? true : false;
var dictionary = createCrossDomainRequest();
var url = 'http://www.math.sjsu.edu/~foster/dictionary.txt';
makeRequest();
function createCrossDomainRequest() {
var request;
if (isIE8) {
request = new window.XDomainRequest();
}
else {
request = new XMLHttpRequest();
}
return request;
}
function makeRequest() {
if (dictionary) {
if(isIE8) {
dictionary.onload = requestSucceeded;
dictionary.open("GET", 'http://www.math.sjsu.edu/~foster/dictionary.txt', true);
dictionary.send();
}
else {
dictionary.open("GET", 'http://www.math.sjsu.edu/~foster/dictionary.txt', true);
dictionary.withCredentials = true;
dictionary.onreadystatechange = handler;
dictionary.send();
}
}
else {
alert("No Invocation Took Place");
}
}
function handler() {
if (dictionary.readyState === 4){
if (dictionary.status == 200){
requestSucceeded();
}
else {
alert("Invocation Errors Occurred");
}
}
}
function requestSucceeded() {
resultText = dictionary.responseText;
document.getElementById( 'demo' ).innerHTML += resultText;
}
你确定IE8没有悄无声息地失败吗?看起来正在绕过handler()并直接调用RequestSuccessed() 您需要为您试图访问的资源(dictionary.txt)设置访问控制允许源标题
如果无法执行此操作,则可以复制文件并将其托管在域中。如果删除
dictionary.withCredentials=true代码>这有什么区别吗?看起来你无法用javascript实现这一点。不过,谢天谢地,您可以从服务器端执行此操作,然后将结果传递到javascript。不,无论我是否使用withCredentials,我使用的是IE11,它都可以工作。我试着将代码放入Firebug中,得到一条“未定义”的消息。Firefox似乎不识别“GET”方法。如何添加访问控制允许来源?我还删除了语句dictionary.onload=requestsuccessed;并将RequestSuccessed函数下的语句移动到handler函数中。它仍然在IE11上运行,但不能在Firefox或Chrome上运行。