2015-11-04 78 views
-1

使用香草XMLHttpRequest()對象爲我創建CORS請求成功,但不使用jQuery.get()函數。然而,$.get()建立在$.ajax()之上,它建立在瀏覽器的XMLHttpRequest()對象之上。原生XMLHttpRequest()成功發出CORS請求,但jQuery .ajax不會?

爲什麼我的jQuery .get()告訴我交叉源請求是不允許的?

撥弄:https://jsfiddle.net/3pwhu05t/

jQuery的()

jQuery.get({url: 'https://www.wikidata.org/wiki/Special:EntityData/Q4231.rdf'}); 
// or 
jQuery.get({url: 'https://www.wikidata.org/wiki/Special:EntityData/Q4231.rdf', 
     crossDomain: true, 
     xhrFields: { 
      withCredentials: true 
      }, 
    }); 

的XMLHttpRequest代碼(從this htlm5rocks.com example截取)

// Create the XHR object. 
function createCORSRequest(method, url) { 
    var xhr = new XMLHttpRequest(); 
    if ("withCredentials" in xhr) { 
    // XHR for Chrome/Firefox/Opera/Safari. 
    xhr.open(method, url, true); 
    } else if (typeof XDomainRequest != "undefined") { 
    // XDomainRequest for IE. 
    xhr = new XDomainRequest(); 
    xhr.open(method, url); 
    } else { 
    // CORS not supported. 
    xhr = null; 
    } 
    return xhr; 
} 

// Make the actual CORS request. 
function makeCorsRequest() { 
    var url = 'https://www.wikidata.org/wiki/Special:EntityData/Q4231.rdf'; 

    var xhr = createCORSRequest('GET', url); 
    if (!xhr) { 
    alert('CORS not supported'); 
    return; 
    } 

    // Response handlers. 
    xhr.onload = function() { 
    var responseText = xhr.responseText; 
    console.log(responseText); 
    }; 

    xhr.onerror = function() { 
    alert('Woops, there was an error making the request.'); 
    }; 

    xhr.send(); 
} 


makeCorsRequest(); 
+1

你測試過什麼瀏覽器? jQuery不會爲IE CORS請求使用'XDomainRequest'。 –

+0

在Chrome中測試 – LazerSharks

+1

方法1工作正常(在Chrome中),方法2失敗,因爲如果allow origin頭被設置爲'*',則不能使用withCredentials。從我的角度來看,似乎按照預期工作。 –

回答

1

jQuery的3.0引入使用jQuery.get的新方法,其允許你傳入一個設置對象。這就是爲什麼jsfiddle工作在邊緣,但不是2.1.4,爲什麼在本地機器上請求本地文件系統,從而給你一個cors錯誤。如果你想使用jQuery.get({url: theurl})語法,你將不得不使用jQuery 3.x,否則你應該使用jQuery.get(theurl)

相關問題