通过$.ajax 跨域请求 chrome 提示 Uncaught SyntaxError: Unexpected token
这是我失败的代码
$.ajax({
type: "get",
url: "http://open.douyucdn.cn/api/RoomApi/live/lol",
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "data",
success: function(response) {
console.log(response);
}
});
[斗鱼 TV API 文档]http://dev-bbs.douyutv.com/forum.php?mod=attachment&aid=MjU5fGQyMzMyMjQ3fDE0ODQzNTc1MzR8MHwxMTM%3D
我去 google 后,了解到返回的数据是 json 格式,但我如果将 dataType 的 value 改成 json 后,又会出现跨域问题。 这期间我尝试使用 script 直接调用该链接,但还是同样的问题, 贴出失败的代码:
var url = "http://open.douyucdn.cn/api/RoomApi/live/lol";
var script = document.createElement("script");
script.setAttribute("src", url);
document.getElementsByTagName("head")[0].appendChild(script);
我觉得我的问题应该归纳为:如何使用 javascript 在跨域条件下调用 json 格式数据? 希望大家能指导我一下,谢谢!
这个问题来源于 freecodecamp 上的一个小题目, [题目地址]: https://www.freecodecamp.com/challenges/use-the-twitchtv-json-api
我只是将其中的 twitch API 改为斗鱼 API