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

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

问题描述

Internet上的某些JSON数据服务被设计为仅由服务器使用,而忽略了仅由Web应用程序直接使用的可能性.

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数据源的代理,然后将其提供给转换为可与JSON一起使用的Web应用程序,CORS或您可以处理的任何其他格式,而不必担心跨站点问题.

**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天全站免登陆