jQuery和CORS [英] jQuery and CORS

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

问题描述

我应该如何处理这个如果服务器不与JSONP响应?我试过几个选项与$阿贾克斯,但不能让它的工作。

codePEN例

  // VAR URL ='https://coinbase.com/api/v1/currencies/exchange_rates';
VAR URL ='http://blockchain.info/ticker';
$阿贾克斯({
    键入:GET,
    网址:网址,
    // jsonpCallback:jsonCallback,
    的contentType:应用/ JSON的,
    //异步:​​假的,
    //数据类型:JSONP,

    // xhrFields:{
    //为CORS?
    // withCredentials:假的
    //},
    成功:函数(JSON){
        调试器;
    },
    错误:函数(JSON){
     调试器;
    }
});
 

解决方案

它看起来像你试图发送一个Ajax请求blockchain.info和检索的JSON提要。幸运的是,他们已经增加了支持CORS。

只要参数 CORS = TRUE 传递到请求的URL(例如, http://blockchain.info/ticker?cors=true ),你应该能够获取数据。

看起来CORS只支持少数API调用按<一个href="https://blockchain.info/api/blockchain_api">https://blockchain.info/api/blockchain_api.

How should I approach this if the server doesn't respond with JSONP? I've tried several options with $.ajax, but can't get it to work.

CodePen Example

//var url = 'https://coinbase.com/api/v1/currencies/exchange_rates';
var url = 'http://blockchain.info/ticker';
$.ajax({
    type: 'GET',
    url: url,
    //jsonpCallback: 'jsonCallback',
    contentType: 'application/json',
    //async: false,
    //dataType: 'jsonp',

    //xhrFields: { 
    // for CORS?
    //  withCredentials: false
    //},
    success: function (json) {
        debugger;
    },
    error: function (json) {
     debugger;
    }
});

解决方案

It looks like you're trying to send an AJAX request to blockchain.info and retrieve the JSON feed. Luckily they've added support for CORS.

Simply pass the parameter cors=true to the requested url (ex. http://blockchain.info/ticker?cors=true) and you should be able to grab the data.

Looks like CORS are only supported for a few API calls as per https://blockchain.info/api/blockchain_api.

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

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