显示json返回undefined

时间:2013-01-24 14:40:50

标签: javascript json

  

可能重复:
  I have a nested data structure / JSON, how can I access a specific value?

基本上我有一个像这样的返回json对象:

"products":[
    {
        "id": "21102165",
        "name": "Eliza J (3/4 sleeve ruched waist dress)",
    }]

我的显示方法:

function getCart(){
var json = $.getJSON('https://'+storedomain+'/cart?'+fcc.session_get()+'&output=json&callback=?');
alert(json['name']);
}

然而,警报显示" undefined"。我在哪里做错了?

由于

3 个答案:

答案 0 :(得分:4)

$.getJSON返回$ .Deferred对象而不是结果

function getCart(){
    $.getJSON('https://'+storedomain+'/cart?'+fcc.session_get()+'&output=json&callback=?', function(data) {
        console.log(data.products[0].name);
    });
}

你可以这样做:

function getCart(){
    return $.getJSON('https://'+storedomain+'/cart?'+fcc.session_get()+'&output=json&callback=?');
}  

$.when(getCart()).then(function(data) {
    console.log(data.products[0].name);
});

答案 1 :(得分:0)

使用成功回调。

var jqxhr = $.getJSON("example.json", function(data, textStatus, jqXHR) {
  alert("success");
})
.success(function(data, textStatus, jqXHR) { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });

请参阅getJSON的API文档。

答案 2 :(得分:0)

你的方法应该是:

function getCart(callback) {
    var url = 'https://'+storedomain + '/cart?'+fcc.session_get()+'&output=json&callback=?';
    $.getJSON(url, callback);
}

// Usage
getCart(function(data) {
    console.log(data.products); // array of car objects
});

或者您可以使用deflex对象,如salexch答案中所述。

您应该熟悉AJAX请求和回调函数的异步特性。

相关问题