Javascript跨域JSON [英] Javascript Cross domain JSON

查看:263
本文介绍了Javascript跨域JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我试图使用 JavaScript HTML 来读取 json 来自URL的对象。我使用下面的代码:

Hi I am trying to use ONLY JavaScript and HTML to read the json object from a URL. I am using the following code:

function getJSONP(url, success) {

    var ud = '_' + +new Date,
        script = document.createElement('script'),
        head = document.getElementsByTagName('head')[0]
            || document.documentElement;

    window[ud] = function(data) {
        head.removeChild(script);
        success && success(data);
    };

    script.src = url.replace('callback=?', 'callback=' + ud);
    head.appendChild(script);
}

getJSONP('http://webURl?&callback=?', function(data){
    console.log(data);
});

正如你所猜到的,我得到 ,并且轨道元素的父代没有crossorigin属性。因此,不允许访问原始null。

As you would have guessed I am getting Not at same origin as the document, and parent of track element does not have a 'crossorigin' attribute. Origin 'null' is therefore not allowed access.

FYI服务器返回JSON数据,并且没有回调函数。

FYI the server returns JSON data and doesnot have callback function.

欢迎您的帮助。

推荐答案

要启用CORS启用使用头像这样:
(信用答案在这里: CORS与PHP的标题

The server either needs to have CORS enabled using headers like this: (Credits to the answer here: CORS with php headers)

// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}

或者服务器需要输出JSONP,如:

Or the server needs to output JSONP like:

echo $_GET['callback'] . '(' . json_encode($whatever) . ')';

另一个选项,如果这不是在你自己的服务器上是在自己的服务器上创建一个PHP文件在你需要读取的url上使用 filegetcontents (使用没有cors的JSON数据),并以JSONP格式回显相同的数据。
然后,您可以在纯JavaScript getJSON 函数中使用此新的PHP文件(url)。

Another option if this is not on your own server is to create a PHP file on your own server that does a filegetcontents on the url you need to read (with the JSON data without cors) and echo the same data in JSONP format. You can then use this new PHP file (url) in your pure javascript getJSON function.

没有中间的服务器或cors或jsonp,这是不可能的。

Without a server in the middle or cors or jsonp, it is not possible.

这篇关于Javascript跨域JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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