我们如何在ajax中编码Multi JSON数据响应

时间:2013-04-08 10:23:13

标签: ajax json jquery

我遇到了通过ajax加载的json编码信息的问题。我将多JSON传递给ajax以显示字段值。

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

ajax代码:

                   ....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). ');';

jsoncallback:

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

1 个答案:

答案 0 :(得分: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响应通过,所以我直接给出。