0

我对通过 ajax 加载的 json 编码信息有疑问。我将多 JSON 传递给 ajax 以显示字段值。

如何使用查询 ajax 从 json 中获取字段值。

阿贾克斯代码:

                   ....success:function(data){
                    var TotalBuyPrice = 0;
                    var TotalItem = 0;
                    $.each(data, function(c,cart){

                        //Condition follow  1
                      var InStockQty =cart.products_qty;
                      alert(InStockQty);

                         //And also follow  2
                       var name =cart["withoutdiscount"][0]["products_name"];
                        alert(name); 

                    });
                     }...

PHP代码:

这些是我对 json 响应的步骤。通过使用数组收集结果

        $response = array();
        $response['withoutdiscount'] = $withoutdiscount;
        $response['withdiscount'] = $withdiscount;

        echo $_GET['jsoncallback'] . '(' . json_encode($response). ');';

json回调:

         ({"withoutdiscount":[{"products_id":"1","products_name":"Lumia"}],
            "withdiscount":[{"products_id":"2","discount_qty":"8"},
                            {"products_id":"3","discount_qty":"1"}
                           ]
          });
4

1 回答 1

0

我解决了这样的问题:使用 PHP 文件得到一个这样的响应:

    $response = array();
    $response['withoutdiscount'] = $withoutdiscount;
    $response['withdiscount'] = $withdiscount;

    echo $_GET['jsoncallback'] . '(' . json_encode($response). ');';

jsoncallback: //JSON 响应

     ({"withoutdiscount":[{"products_id":"1","products_name":"Lumia"}],
        "withdiscount":[{"products_id":"2","discount_qty":"8"},
                        {"products_id":"3","discount_qty":"1"}
                       ]
      });

使用 ajax 函数调用 json 响应,如下所示:

        function querySuccess(tx,results) {
            var jsonString = JSON.stringify(results);
            $.ajax({
                url:'getcart.php',
                data: {data : jsonString},
                dataType: 'jsonp',
                jsonp: 'jsoncallback',
                timeout: 5000,
                success:function(data){
                    var withdiscount=data.withdiscount;
                    var withoutdiscount=data.withoutdiscount;
                if(withdiscount!='')
                {
                    $.each(withdiscount, function(c,cart){
                       var discount_qty =cart.discount_qty;
                        alert(discount_qty);
                     );
                 }
                if(withoutdiscount!='')
                {
                    $.each(withoutdiscount, function(c,cart){ 
                       var products_name =cart.products_name;
                          alert(products_name);
                     });
                }
               }
            });
        }

这和我一起工作。

注意:只有 2 个 JSON 响应通过,所以我直接给出。

于 2013-04-09T10:23:24.057 回答