如何从既没有 CORS 也没有 JSONP 的源在网页上使用 JSON? [英] How can I use JSON on the web page from a source with neither CORS nor JSONP?

查看:16
本文介绍了如何从既没有 CORS 也没有 JSONP 的源在网页上使用 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

互联网上的一些 JSON 数据服务被设计为仅供服务器使用,而忽略了被纯网络应用直接使用的可能性.

Some JSON data services on the Internet are designed to be consumed only by servers and neglect the possibility of being consumed directly by a web-only app.

由于跨站点问题,如果此类服务提供 JSONP 格式或启用 CORS 支持.

Due to cross-site concerns, such services would work if they either provided a JSONP format or enabled CORS support.

我想做一个 JavaScript 小工具,可以调用只返回 JSON 而不是返回的在线资源,并且不支持 .

I want to make a little JavaScript tool that can call an online resource that only returns JSON and not , and does not support .

一个例子是我正在制作的单页应用程序,我能找到的唯一数据源没有提供 CORSJSONP.作为一个单页应用,它没有自己的服务器,因此受同源政策的约束.

One example case was a single-page app I was making for which the only data source I could find didn't provide CORS or JSONP. Being a single-page app, it had no server of its own so was subject to the same-origin policy.

在这种情况下有哪些可用的策略?

What strategies are available in such cases?

推荐答案

**一种方法是找到一个可以访问 JSON 数据源的代理,然后将其提供给您的 Web 应用程序转换为使用 JSONCORS 或任何其他您可以处理的格式,而无需担心跨站点问题.

**One way is to find a proxy that can access a JSON data source and then serve it to your web app transformed to work with JSON, CORS, or any other format that you can handle without worrying about cross-site concerns.

一个这样的代理是雅虎的YQL".

YQL 同时支持 JSONP 和 CORS.

YQL supports both JSONP and CORS.

因此,如果您的浏览器也支持 CORS,您可以将其视为免费的 JSON 到 JSON 代理服务器.如果没有,那么它也是一个免费的 JSON 到 JSONP 代理:

So if your browser also supports CORS you can think of it as a free JSON to JSON proxy server. If not, then it is also a free JSON to JSONP proxy:

这是我如何将它与 jQuery 一起使用的示例:

Here's an example of how I used it with jQuery:

$.getJSON("http://query.yahooapis.com/v1/public/yql",
  {
    q:      "select * from json where url="http://airportcode.riobard.com/airport/" + code + "?fmt=JSON"",
    callback: gotJSON, // you don't even need this line if your browser supports CORS
    format: "json"
  },
  function(data){
    if (data.query.results) {
      /* do something with
        data.query.results.json.code
        data.query.results.json.name
        data.query.results.json.location
      */
    } else {
      /* no info for this code */
    }
  }
);

还有一个关于 jsfiddle 的版本...

这篇关于如何从既没有 CORS 也没有 JSONP 的源在网页上使用 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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