从 JavaScript 的 API 加载 JSON 数据
我需要使用一个 Web api,它位于此处 http://46.253.202.174:8080/ws-api/v1/rest/zdata/codesByJurAndUsage?jur=Boston,%20MA&usg=barber
我没有任何详细信息它是如何实现或访问 API 代码的,我只是想使用 API,如果我输入以下内容,我可以看到 JSON 返回数据url 在浏览器中,但是当我尝试使用 $.getJSON 调用 API 时,它给了我一个访问被拒绝的错误。据我了解,这是一个跨域问题。我还尝试了其他一些东西,例如 jsonp 数据类型,但没有成功。我的问题是,如果我能够在浏览器中看到结果,我是否应该能够从脚本中获取结果,或者它不一定是真的? 其次,如果我到目前为止尝试过的事情不成功,还有其他方法吗?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是对的,由于 同源政策限制。您需要通过 JSONP 加载它,或者,如果服务不支持 JSONP(看起来不支持),则通过代理加载。有几个选项:
您可以通过 PHP 或其他服务器端语言在您自己的服务器上设置代理。这将允许您从自己的服务器请求数据,从而绕过同源限制。为此,您可能会考虑 Simple PHP Proxy 之类的项目。
您可以使用YQL作为代理< /a> - 这会通过 Yahoo! 的服务器发送数据,然后您可以通过 JSONP 加载它。 本文讨论了如何在 jQuery 中应用此技术。< /p>
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.