問題描述
我寫了一個 XMLHttpRequest,它運行良好但返回一個空的 responseText.
I have written an XMLHttpRequest which runs fine but returns an empty responseText.
javascript如下:
The javascript is as follows:
var anUrl = "http://api.xxx.com/rates/csv/rates.txt";
var myRequest = new XMLHttpRequest();
callAjax(anUrl);
function callAjax(url) {
myRequest.open("GET", url, true);
myRequest.onreadystatechange = responseAjax;
myRequest.setRequestHeader("Cache-Control", "no-cache");
myRequest.send(null);
}
function responseAjax() {
if(myRequest.readyState == 4) {
if(myRequest.status == 200) {
result = myRequest.responseText;
alert(result);
alert("we made it");
} else {
alert( " An error has occurred: " + myRequest.statusText);
}
}
}
代碼運行良好.我可以走過去,我得到了 readyState == 4 和一個狀態 == 200 但 responseText 總是空白.
The code runs fine. I can walk through and I get the readyState == 4 and a status == 200 but the responseText is always blank.
我收到錯誤調度的日志錯誤(在 Safari 調試中):getProperties,我似乎無法找到參考.
I am getting a log error (in Safari debug) of Error dispatching: getProperties which I cannot seem to find reference to.
我已經在本地和遠程服務器上的 Safari 和 Firefox 中運行了代碼.
I have run the code in Safari and Firefox both locally and on a remote server.
將 URL 放入瀏覽器時將返回字符串并給出狀態碼 200.
The URL when put into a browser will return the string and give a status code of 200.
我在一個運行良好的 Mac Widget 中為相同的 URL 編寫了類似的代碼,但在瀏覽器中的相同代碼永遠不會返回結果.
I wrote similar code to the same URL in a Mac Widget which runs fine, but the same code in a browser never returns a result.
推薦答案
http://api.xxx.com/
是否屬于您的域?如果沒有,您將被同源政策阻止.
Is http://api.xxx.com/
part of your domain? If not, you are being blocked by the same origin policy.
您可能需要查看以下 Stack Overflow 帖子,了解一些可能的解決方法:
You may want to check out the following Stack Overflow post for a few possible workarounds:
- 規避同源策略的方法
這篇關于來自 XMLHttpRequest 的空 responseText的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!