从AJAX请求返回奇怪的对象

时间:2016-02-12 05:00:23

标签: ajax

我有这个方法:

    var chineseCurrency = getChinese();
    function getChinese(){
        return $.ajax({
            context: this,
            type: 'GET',
            dataType: 'json',
            url: "https://www.cryptonator.com/api/ticker/usd-cny"
        });
    }

这是console.log(chineseCurrency);

时打印的内容

enter image description here

我无法使chineseCurrency等于"price",因此它会"6.80071377"。我怎样才能做到这一点?试过chineseCurrency.responseText,不,chineseCurrency['responseText'],不。试图JSON.parse(chineseCurrency),不。什么都行不通!

很抱歉,如果重复,无法在Stackoverflow找到任何答案。

2 个答案:

答案 0 :(得分:1)

How do I return the response from an asynchronous call?

无法从调用$.ajax的函数返回作为对异步ajax调用的响应而接收的数据。您要返回的是XMLHttpRequest对象(请参阅http://api.jquery.com/jquery.ajax/),该对象远离所需数据。

var chineseCurrency = null;
function getChinese(){
    return $.ajax({
        context: this,
        type: 'GET',
        dataType: 'json',
        url: "https://www.cryptonator.com/api/ticker/usd-cny",
        success: function(data) {
            alert("success1: chineseCurrency=" + chineseCurrency); 
            chineseCurrency = data.ticker.price;
            alert("success2: chineseCurrency=" + chineseCurrency);
            // do what you need with chineseCurrency 
        }
    });
}

答案 1 :(得分:0)

您没有从Ajax调用返回的数据。相反,你只是返回ajax对象。

将您的代码更改为:

    $.ajax(
    {
        context: this,
        type: 'GET',
        dataType: 'json',
        url: "https://www.cryptonator.com/api/ticker/usd-cny"
        data    :{},
        error   : function(data)
        {
            console.log('error occured when trying to find the from city');
        },
        success : function(data) 
        {
           console.log(data); //This is what you should return from the function. 
        }
   });