如何从URL读取JSON响应并使用Javascript内部的键和值(数组内部的数组)

时间:2016-11-28 14:48:57

标签: javascript php arrays json ajax

我的控制器功能:

"

来自URL的我的JSON响应是: public function displayAction(Request $request) { $stat = $this->get("app_bundle.helper.display_helper"); $displayData = $stat->generateStat(); return new JsonResponse($displayData); }

从这个Response我希望将值传递给javascript文件中的变量(selfie,shared),如:

{"Total":[{"date":"2016-11-28","selfies":8},{"date":"2016-11-29","selfies":5}],"Shared":[{"date":"2016-11-28","shares":5},{"date":"2016-11-29","shares":2}]}

4 个答案:

答案 0 :(得分:1)

你可以这样试试。

首先遍历顶层对象数据,然后遍历作为数组的数据的每个属性。



var data = {"total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2},{"date":"2016-11-30","selfies":0},{"date":"2016-12-01","selfies":0},{"date":"2016-12-02","selfies":0},{"date":"2016-12-03","selfies":0},{"date":"2016-12-04","selfies":0}],"shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0},{"date":"2016-11-30","shares":0},{"date":"2016-12-01","shares":0},{"date":"2016-12-02","shares":0},{"date":"2016-12-03","shares":0},{"date":"2016-12-04","shares":0}]}

Object.keys(data).forEach(function(k){
  
   var val = data[k];
   
    val.forEach(function(element) {
    console.log(element.date);
    console.log(element.selfies != undefined ? element.selfies : element.shares );
      
    });
   
});




答案 1 :(得分:0)

在回调中使用以下内容:

$.each(data.total, function(i, o){
    console.log(o.selfies);
    console.log(o.date);

    // or do whatever you want here
})

因为您使用jetJSON发出请求,所以发送给回调的参数data已经是一个对象,因此您不需要解析响应。

答案 2 :(得分:0)

试试这个:

var text ='{"Total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2}],"Shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0}]}';

var jsonObj = JSON.parse(text);

var objKeys = Object.keys(jsonObj);

for (var i in objKeys) {
   var totalSharedObj = jsonObj[objKeys[i]];
   if(objKeys[i] == 'Total') {
     for (var j in totalSharedObj) {
     document.getElementById("demo").innerHTML +=
  "selfies on "+totalSharedObj[j].date+":"+totalSharedObj[j].selfies+"<br>";
   }
   }
   if(objKeys[i] == 'Shared') {
     for (var k in totalSharedObj) {
     document.getElementById("demo").innerHTML +=
  "shares on "+totalSharedObj[k].date+":"+totalSharedObj[k].shares+"<br>";
   }
   }
}
<div id="demo">

</div>

答案 3 :(得分:0)

我做了很多研究&amp;从其他用户那里获得帮助,最终可以解决我的问题。所以想到分享我的解决方案。

$.get( "Address for my JSON data", function( data ) {


        var selfie =[];
        $(data.Total).each(function(){
            var tmp = [
                this.date,
                this.selfies
            ];
            selfie.push(tmp);
        });
        var shared =[];
        $(data.Shared).each(function(){
            var tmp = [
                this.date,
                this.shares
            ];
            shared.push(tmp);
        });
});