loading JSON data from an API from javascript

微笑、不失礼 提交于 2019-12-07 22:30:51

问题


i need to consume a web api, which is located here http://46.253.202.174:8080/ws-api/v1/rest/zdata/codesByJurAndUsage?jur=Boston,%20MA&usg=barber

I don't have any details of how it is implemented or access to the code of the API, I'm just trying to consuming the API, I can see the JSON return data if i type the url in the browser, but when i'm trying to call the API using $.getJSON, it gave me an access denied error. I understand that its a cross domain issue. I also tried a few other things, like jsonp data type, with no success. My question is, if i am able to see the results in a browser, shouldn't i be able to get the results from the scripts, or its no necessarily true? Secondly, is there any other way, if the things i have tried so far was not successful.

thanks


回答1:


You are correct, you won't be able to load this data via $.getJSON due to the Same Origin Policy restrictions. You'll need to load it via JSONP, or, if the service doesn't support JSONP (which it looks like it doesn't), via a proxy. A couple of options:

  • You can set up a proxy on your own server via PHP or another server-side language. This will allow you to request the data from your own server, getting around the same-origin restriction. You might look at a project like Simple PHP Proxy for this purpose.

  • You can use YQL as a proxy - this sends the data through Yahoo!'s servers and then you can load it via JSONP. Applying this technique with jQuery is discussed in this article.



来源:https://stackoverflow.com/questions/6673538/loading-json-data-from-an-api-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!