Javascript跨域JSON

usr*_*und 9 javascript jsonp cross-domain

嗨,我正在尝试使用ONLY JavaScript并从URL HTML读取json对象.我使用以下代码:

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);
});
Run Code Online (Sandbox Code Playgroud)

正如你猜想的那样 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.

仅供参考,服务器返回JSON数据,但没有回调函数.

干杯,为您提供帮助.

Bas*_*ein 7

服务器需要使用这样的标头启用CORS :(这里的答案可信:带有php标头的CORS)

// 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);
}
Run Code Online (Sandbox Code Playgroud)

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

echo $_GET['callback'] . '(' . json_encode($whatever) . ')';
Run Code Online (Sandbox Code Playgroud)

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

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