2015-07-20 142 views
4

如何通過ajax從遠程URL獲取內容?jQuery ajax請求被阻止,因爲跨源

jQuery的Ajax請求是塊,因爲跨來源

控制檯登錄

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.dailymotion.com/embed/video/x28j5hv . (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.dailymotion.com/embed/video/x28j5hv . (Reason: CORS request failed).

代碼

$.ajax({ 
url: "http://www.dailymotion.com/embed/video/x28j5hv", 
type:'GET', 
contentType: "html", 
crossDomain:true, 
success: function(data){ 
    //$('#content').html($(data).html()); 
    var src = $(data).html(); 
    alert(src); 
    return false; 
} 
+0

@ D4V1D對不起,我忘了將它加入到我的問題。如何通過Ajax從遠程URL獲取內容? –

+1

設置'crossDomain:true'不會設置跨域請求。該網站必須啓用CORS才能正常工作。 –

+0

@RoyiNamir你能解釋一下嗎?我是jquery的新手。 –

回答

8

嘗試在您的Ajax調用中使用JSONP。它將繞過同源策略。

http://learn.jquery.com/ajax/working-with-jsonp/

嘗試例如

$.ajax({ 
    url: "https://api.dailymotion.com/video/x28j5hv?fields=title", 

    dataType: "jsonp", 
    success: function(response) { 
     console.log(response); // server response 
    } 

}); 
+6

jsonp實際上工作,但響應數據顯示我錯誤。 'SyntaxError:missing;之前的聲明 \t {「result」:[{「id」:1,「cat_name」:「travel」,「imgpath」:「http:\/adas \/asd」 「result」,這是什麼意思? –

+0

這意味着它不能解析響應。當你使用jsonp時,響應應該是類似於CALLBACK({... JSON ...})。你可以定義CALLBACK指定「 jsonpCallback「放在你的ajax參數中,或者它將隨機生成並作爲名爲」callback「的字段發送到請求中 – chrmcpn

2

沒有什麼,你可以在你做到底(客戶端)。您無法自行啓用跨域調用,源(dailymotion.com)需要啓用COORS才能運行。

你真的可以做的唯一事情就是創建一個服務器端代理腳本,爲你做到這一點。你在你的項目中使用任何服務器端腳本? PHP,Python,ASP.NET等?如果是這樣,你可以創建一個服務器端的「代理」腳本,使HTTP調用dailymotion並返回響應。然後,從Javascript代碼中調用該腳本,因爲該服務器端腳本與腳本代碼位於同一個域中,所以COORS不會成爲問題。

相關問題