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
CodePudding user response:
As you can see, I'm trying to fetch is as jsonp, hence why I added " ?callback=? " at the end of the url
The server doesn't support JSONP (and shouldn't, it is a dirty hack with security issues and we have CORS now).
Either:
- Change the server to support JSONP (not recommended; see above)
- Remove
?callback=?
and change the server to grant your JS permission to read the data using CORS - Don't fetch the data directly from the client (e.g. proxy it through your own server).