如果大于0,则jQuery $ .post数据分配给vaiable

时间:2016-03-22 07:17:13

标签: javascript jquery

我使用jquery $ .post

从MySQL调用数据
var fruitInfo ='';
$.post('test.php',
        {
          b:'fruits'
        },
        function(data){
          //console.log(data[0]['val1']);
          for(var i=0; i<data.length; ++i) {
              //if data[0]['appleStocks'] is not 0 -> `fruitInfo` += '<p>appleStocks</p>'
              //if data[0]['grapesStocks'] is not 0 -> `fruitInfo` += '<p>grapesStocks</p>'
              //check if custom data is not 0 add to `fruitInfo`
          }
        });

我的问题是,如果返回的值不是0,我需要将收到的某些字段值添加到fruitInfo。这些自定义字段是否应存储在要检查的数组中?我该怎么做?

例如: php返回

storeNumber = 123, 
grapeTypes = a,b,
AppleTypes = b,
LycheeTypes = a,b,
grapeStocks = 91,
appleStocks = 0,
lycheeStocks = 25,

使用(data[0]['grapeStocks']data[0]['appleStocks']data[0]['lycheeStocks']我希望能够更新var fruitInfo,如下所示

fruitInfo = '<p>grapeStocks = 91, lycheeStocks = 25</p>';

1 个答案:

答案 0 :(得分:1)

将回调处理程序中的for循环更改为

     var fruits = {"appleStocks" : 0, "grapesStocks" : 0};
     for(var i=0; i<data.length; ++i) {

          if (data[0]['appleStocks'] > 0 ){ fruits[appleStocks] += data[0]['appleStocks'] }
          else if (data[0]['grapesStocks'] > 0 ){ fruits[grapesStocks] += data[0]['grapesStocks'] }
     }
     var fruitInfo = "<p>" + Object.keys(fruits).map(function(value){return key + "=" + fruits[key];}).join(" , ") + "</p>" ;