[英]Trouble receiving JSON data from nodejs application?
The below jQuery ajax method makes a call to node.js application that returns a json formatted data. 下面的jQuery ajax方法调用node.js应用程序,该应用程序返回json格式的数据。 I did check the console and it returns the json in this format
我确实检查了控制台,它以这种格式返回了json
{ "SQLDB_ASSIGNED": 607, "SQLDB_POOLED":285, "SQLDB_RELEVANT":892, "SQLDB_TOTSERVERS":19}
However, when i try to access the element using the key name i get "undefined" on the console ? 但是,当我尝试使用键名访问元素时,在控制台上得到“未定义”?
Nodejs Nodejs的
res.send(JSON.stringify(" { \"SQLDB_ASSIGNED\": "+assigned_tot+", \"SQLDB_POOLED\":"+pooled_tot+", \"SQLDB_RELEVANT\":"+relevant_tot+", \"SQLDB_TOTSERVERS\":"+servertotal+"}"));
Jquery Ajax jQuery Ajax
$.ajax({
url: '/currentdata',
async: false,
dataType: 'json',
success: function (data) {
console.log(data);
for(var i in data)
{
console.log(data[i].SQLDB_ASSIGNED+"---"+data[i].SQLDB_POOLED+"---"+data[i].SQLDB_RELEVANT+"---"+data[i].SQLDB_TOTSERVERS );
}
}
});
Your Node.js part is very weird. 您的Node.js部分非常奇怪。 You are stringifying a string:
您正在字符串化:
res.send(JSON.stringify(" { \"SQLDB_ASSIGNED\": "+assigned_tot+", \"SQLDB_POOLED\":"+pooled_tot+", \"SQLDB_RELEVANT\":"+relevant_tot+", \"SQLDB_TOTSERVERS\":"+servertotal+"}"));
Why not just this? 为什么不只是这个呢? That's probably what you are looking for:
这可能是您要寻找的:
res.send(JSON.stringify({
SQLDB_ASSIGNED: assigned_tot,
SQLDB_POOLED: pooled_tot,
SQLDB_RELEVANT: relevant_tot,
SQLDB_TOTSERVERS: servertotal
}));
And then in the callback just this: 然后在回调中这样:
data.SQLDB_ASSIGNED; // Here you go
I don't know why you are iterating over the keys of the json. 我不知道您为什么要遍历json的键。 You want this:
你要这个:
console.log(data.SQLDB_ASSIGNED+"---"+data.SQLDB_POOLED+"---"+data.SQLDB_RELEVANT+"---"+data.SQLDB_TOTSERVERS );
So the code would be: 因此,代码将是:
$.ajax({
url: '/currentdata',
async: false,
dataType: 'json',
success: function (data) {
console.log(data.SQLDB_ASSIGNED+"---"+data.SQLDB_POOLED+"---"+data.SQLDB_RELEVANT+"---"+data.SQLDB_TOTSERVERS );
}
});
You seem to be treating the data variable as an array of objects, containing the keys you specify. 您似乎将数据变量视为对象数组,其中包含您指定的键。 I guess what you would like to do is this:
我想您想做的是:
for(var key in data) {
console.log(key+": "+data[key]);
}
Or what? 要不然是啥?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.