从JavaScript加载来自API的JSON数据 [英] loading JSON data from an API from javascript

查看:166
本文介绍了从JavaScript加载来自API的JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用一个web api,它位于这里
http://46.253.202.174:8080/ws-api/v1/rest/zdata/codesByJurAndUsage?jur=Boston,%20MA&usg=barber

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

我没有关于如何实现或访问API代码的任何细节,我只是想尝试使用API​​,我可以看到JSON如果我在浏览器中输入网址,则返回数据,但是当我尝试使用$ .getJSON调用API时,它会给我一个访问被拒绝错误。我理解这是一个跨域问题。我还尝试了一些其他的东西,比如jsonp数据类型,没有成功。我的问题是,如果我能够在浏览器中看到结果,我不应该从脚本中获得结果,或者它不一定是真的吗?
其次,有没有其他办法,如果我迄今为止尝试的事情都不成功。

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.

谢谢

推荐答案

你是对的,你不会是由于,可以通过 $。getJSON 加载此数据同源政策限制。您需要通过JSONP加载它,或者,如果该服务不支持JSONP(它看起来不是这样),则通过代理加载它。几个选项:

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:


  • 您可以通过PHP或其他服务器端语言在自己的服务器上设置代理。这将允许您从您自己的服务器请求数据,绕过同源限制。您可以为此目的查看简单PHP代理等项目。

您可以使用 YQL作为代理 - 它通过Yahoo!的服务器发送数据,然后你可以通过JSONP加载它。将此技术应用于jQuery是本文中讨论的

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.

这篇关于从JavaScript加载来自API的JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆