如何使用 javascript 和/或 jquery 从外部 url 获取 json?
我试图从此网址获取一些 json : http:// /api.conceptnet.io/query?rel=/r/UsedFor&limit=3
我有一个调用函数“jsonplz()”的按钮,该按钮应该向我发出有关获取的警报json。
我的javascript看起来像这样:
<script src="http://code.jquery.com/jquery-3.3.1.min.js">
</script>
<script>
function jsonplz(){
$.getJSON("http://api.conceptnet.io/query?rel=/r/UsedFor&limit=3?callback=?",function(json){
console.log(json);
});
}
</script>
如你所见,我试图获取jsonp,因此为什么我在url末尾添加“?callback=?”,否则如果我试图将其获取为json,我的浏览器会阻止我。
问题是:它仍然不起作用。当我调用 jsonplz() 时,我在 Firefox 控制台上收到此错误:
警告:来自的脚本“https://api.conceptnet.io/query?rel=/r/UsedFor&limit=3?callback=jQuery331030366838930478535_1646253265514&_=1646253265515”已加载,即使其 MIME 类型(“application/json”)不是有效的JavaScript MIME 类型。
错误:未捕获的语法错误:意外标记:':'
任何解决此错误的解决方案或任何其他方式从外部网址检索 json 而不下载额外的第三方软件是赞赏
I'm trying to get some json from this url : http://api.conceptnet.io/query?rel=/r/UsedFor&limit=3
I have a button that calls the function "jsonplz()" which is supposed to give me an alert with the fetched json.
My javascript looks something like this :
<script src="http://code.jquery.com/jquery-3.3.1.min.js">
</script>
<script>
function jsonplz(){
$.getJSON("http://api.conceptnet.io/query?rel=/r/UsedFor&limit=3?callback=?",function(json){
console.log(json);
});
}
</script>
As you can see, I'm trying to fetch is as jsonp, hence why I added " ?callback=? " at the end of the url, otherwise if I was trying to get it as json, my browser would have blocked me.
Here's the problem : it still doesn't work. I get this error on the firefox console when I call jsonplz() :
Warning : The script from “https://api.conceptnet.io/query?rel=/r/UsedFor&limit=3?callback=jQuery331030366838930478535_1646253265514&_=1646253265515” was loaded even though its MIME type (“application/json”) is not a valid JavaScript MIME type.
Error : Uncaught SyntaxError: unexpected token: ':'
Any solution to either solve this error or any other way to retrieve json from an external url without downloading additional third party software is appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
服务器不支持 JSONP(也不应该,这是一个肮脏的黑客行为安全问题,我们现在有 CORS)。
要么:
?callback=?
并更改服务器以授予 JS 使用 CORS 读取数据的权限The server doesn't support JSONP (and shouldn't, it is a dirty hack with security issues and we have CORS now).
Either:
?callback=?
and change the server to grant your JS permission to read the data using CORS