javascript - XMLHttpRequest 無法載入,因為來源被 Access-Control-Allow-Origin 不允許
我正在嘗試通過 XHR 獲取一個 http:// 的 JavaScript 文件,但我遇到了上面提到的錯誤。
這是我的程式碼:
function getXHR() {
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if (is_chrome) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.widgets.org/widget/1.1.2/widget_api.js?autoCreate=false&log=true", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var s = document.createElement('script');
s.textContent = xhr.responseText;
(document.head||document.documentElement).appendChild(s);
s.parentNode.removeChild(s);
}
}
xhr.send();
}
}
這僅適用於 Chrome,因為我想在 https:// 上使用這個腳本,但 Chrome 會自動阻擋來自 http:// 的任何內容。我獲取腳本的伺服器不提供 https://,而我需要這個腳本/有多個腳本,我不希望全部複製到資料檔案中。
我遇到的錯誤:
XMLHttpRequest cannot load http://api.widgets.org/widget/1.1.2/widget_api.js?autoCreate=false&log=true. Origin https://mysite.com is not allowed by Access-Control-Allow-Origin.
答案#1
只需直接插入 <script> 標籤,而不是使用這個 XHR 包裝器,然後將內容插入到 <script> 標籤中。
function getScript() {
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if (is_chrome) {
// generate script element and set its source
var s = document.createElement('script');
s.src = "http://api.widgets.org/widget/1.1.2/widget_api.js?autoCreate=false&log=true";
// remove the script element after loading
s.addEventListener( 'load', function(){ s.parentNode.removeChild(s); } );
(document.head||document.documentElement).appendChild(s);
}
}
此外,我不知道你為什麼在加載後還試圖移除 script 元素。這不會影響該代碼中創建的任何對象/方法/變量。
答案#2
我將伺服器檔案的完整路徑更改為以下的短路徑。
$.post('http://example.com/pages/loadRandomImages.php',{'type':'loadRandomImages','loadingReq':'True'},function(data){
------------
----------
});
改成了,
$.post('/pages/loadRandomImages.php',{'type':'loadRandomImages','loadingReq':'True'},function(data){
------------
----------
});
然後在 Chrome 中運作正常。
