[英]javascript how to get json data with api call to redirected url
我正在從gltich API獲取json數據。
當我轉到該鏈接時,URL重定向到另一個域
https://wind-bow.glitch.me/twitch-api/users/freecodecamp
(域名從
gomix.me
更改為glitch.me
)
對兩個HTTP請求使用郵遞員 ,我得到相同的JSON數據。 但是,當使用jQuery .getJSON
方法時,兩者不會產生相同的結果
$(document).ready(function() { $.getJSON("https://wind-bow.gomix.me/twitch-api/users/freecodecamp", function(data1) { console.log("Gomix.me URL", data1); // nothing outputted }); $.getJSON("https://wind-bow.glitch.me/twitch-api/users/freecodecamp", function(data2) { console.log("Glitch.me URL", data2); // expected data outputted }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
是否可以通過將重定向到gomix.me
的URL獲取JSON數據,或者我只能僅使用最終端點glitch.me
?
Gomix請求被CORS政策阻止。 您可以使用此heroku應用程序繞過它: https : //cors-anywhere.herokuapp.com/ 。
$(document).ready(function() { $.getJSON("https://cors-anywhere.herokuapp.com/https://wind-bow.gomix.me/twitch-api/users/freecodecamp", function(data1) { console.log("Gomix.me URL", data1); // now it works }); $.getJSON("https://wind-bow.glitch.me/twitch-api/users/freecodecamp", function(data2) { console.log("Glitch.me URL", data2); // expected data outputted }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
如果您將$.ajax
與dataType: 'jsonp'
它將為您提供幫助。
$(document).ready(function() {
$.ajax({
url: "https://wind-bow.gomix.me/twitch-api/users/freecodecamp",
type: 'GET',
dataType: 'jsonp',
success: function(data1) { console.log("Gomix.me URL", data1);}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.