jQuery Ajax / .each回调不返回值

时间:2014-06-12 12:36:40

标签: javascript php ajax json

我有这个脚本,所以当我点击按钮时我必须得到值,但是返回null和0值:

SCRIPT:

$(function(){
        $("#update_totais").live('click', function(){
            var url="check_totals.php?id_rasc=1";
            $.getJSON(url,function(data){
                $.each(data.totais, function(i,values){
                    total_iliquido = values.total_iliquido;
                    descontos = values.descontos;
                    iva = values.iva;
                    total = values.total2;
            alert(total);
                });
            });
        });
    });

JSON RETURN:

{"totais":[{"total_iliquido":"1500.00","descontos":"0.00","iva":345,"total2":1845}]}

我猜一切正常,为什么给我NULL和0值?

1 个答案:

答案 0 :(得分:0)

为了访问您需要索引和密钥的值,您不够深入:

var totais = {"totais":[{"total_iliquido":"1500.00","descontos":"0.00","iva":345,"total2":1845}]};
totais['totais'][0]['iva'] -> 345

所以试试这个:

var index = 0;
$.each(totais, function(i,values){  
    total_iliquido = values[index]['total_iliquido'];
    descontos = values[index]['descontos'];
    iva = values[index]['iva'];
    total = values[index]['total2'];
    console.log(values[index]['total2']);
  index++;
});

函数中的变量i包含对象的名称而不是成员的索引。