2014-09-27 120 views
0

對不起復制這個問題的一個問題,但我真的試圖尋求一個解決方案,但我找不到它。所以我使用angular $ http.get xhr請求從public api中檢索數據。我有一個代碼

$http.get('http://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes&year=2000&sold_in_us=1') 
    .success(function(d){ console.log(d); }) 
    .error(function(d){ console.log("nope"); 
}); 

這個返回控制檯:

XMLHttpRequest cannot load http://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes&year=2009. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'blah-my-localhost-blah' is therefore not allowed access. 

但是,如果我用戶的jQuery的getJSON方法只是正常工作:

$.getJSON("http://www.carqueryapi.com/api/0.3/?callback=?", {cmd:"getMakes", year:"2009"},      
    function(data) { 
    console.log(data); 
    }); 

所以,很顯然,我可以配置的角度發送正確的請求,因爲jQuery工作正常?

謝謝你的迴應。

+0

的Jquery的getJSON使用JSONP回調以來參數,URL – danronmoon 2014-09-27 22:56:33

+0

角度存在不使用''呢?回調的方式jQuery的...閱讀正確的回調字符串的文檔,並使用'$ http.jsonp'https://docs.angularjs.org/api/ng/service/$http#jsonp – charlietfl 2014-09-27 22:59:08

回答

2

使用$http.jsonp方法做JSON_CALLBACK爲回調名字一起JSONP請求:

$http.jsonp('http://www.carqueryapi.com/api/0.3/?callback=JSON_CALLBACK&cmd=getMakes&year=2000&sold_in_us=1') 
    .success(function(d){ console.log(d); }) 
    .error(function(d){ console.log("nope"); }); 
+0

什麼是奇怪的'回調= JSON_CALLBACK'參數呢?一些解釋將不勝感激。 – scaryguy 2016-05-25 19:09:10

相關問題