使用jquery

时间:2018-08-16 10:18:11

标签: jquery json rest api

我已经通过ajax调用了rest api,我得到了json格式的api响应,现在我想在网页上显示数据。 我想显示如下

scheduled
driver_count:
passenger_count:

active
driver_count:
passenger_count:

我的代码如下

$(document).ready(function() {
        $.ajax({
            asyn: true,
            crossDomain: true,
            url: "http://10.26.32.11/api/rating-service/rate/current/gettrips",
            dataType: 'JSON',
            callback: 'callback',
            type: 'GET',
            success: function(data) {
                var jso = parseJSON(data);
                console.log(jso);                    

            }
        });

    });

JSON回复

{
"scheduled": {
    "driver_count": 1,
    "passenger_count": 1
},
"active": {
    "driver_count": 0,
    "passenger_count": 0
}

}

4 个答案:

答案 0 :(得分:1)

这里:

// jsonreplay is the string of json you got from the server
var obj = JSON.parse(jsonreplay)
// in javascript you can use for loop to iterate properties
for(var propertyName in obj){
   console.log(propertyName+":");
   for(var internalPropertyName in obj[propertyName]){
      console.log(internalPropertyName + ":"+obj[propertyName][internalPropertyName]);
   }
}

答案 1 :(得分:0)

您可以按照以下说明访问变量

jso.active.driver_count // will print out your value

答案 2 :(得分:0)

如果您不是自己制作此api,则可以循环对象

var jsobj = {
            "scheduled": {
                            "driver_count": 1,
                            "passenger_count": 1
                         },
            "active":    {
                         "driver_count": 0,
                         "passenger_count": 0
                         }
            };

for (var key in jsobj) {
    if (jsobj.hasOwnProperty(key)) {
        console.log(key); //scheduled, active
        var d_cnt = jsobj[key]['driver_count'];
        var p_cnt = jsobj[key]['passenger_count'];
    }
}    

但是,如果您可以编辑api输出脚本,则此结构将使工作更轻松:

var objList = [{
            "type" : "scheduled", 
            "driver_count": 1,
            "passenger_count": 1
          },{
            "type": "active",
            "driver_count": 0,
            "passenger_count": 0
          }];

答案 3 :(得分:0)

您可以将新变量创建为具有值的key_count并使用该变量

obj = {
"scheduled": {
    "driver_count": 1,
    "passenger_count": 1
},
"active": {
    "driver_count": 0,
    "passenger_count": 0
}}
makeFlatModel(obj);
console.log(obj);

function makeFlatModel(jsonObject){
	var sum=0;
	for(var propertyName in jsonObject){
		if(typeof jsonObject[propertyName] =='object'){
			jsonObject[propertyName+"_count"] = makeFlatModel(jsonObject[propertyName]);
		}else{
			sum+= jsonObject[propertyName];
		}
	} 
  return sum;

}

输出 enter image description here