Javascript Cross domain JSON

一个人想着一个人 提交于 2019-12-23 07:38:47

问题


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);
});

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 the server returns JSON data and doesnot have callback function.

Cheers for your help.


回答1:


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);
}

Or the server needs to output JSONP like:

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

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.

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




回答2:


If you want a quick & working fix, you can fetch the content via an iframe, or use a proxy like YQL.

But I would recommend using a backend strategy to fetch your content, then process it with javascript.



来源:https://stackoverflow.com/questions/32302518/javascript-cross-domain-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!