[英]jQuery.get read values from data
I cannot seem to access the values in the returned data array from a jQuery.getJSON and I cannot understand why. 我似乎无法从jQuery.getJSON访问返回的数据数组中的值,而且我也不明白为什么。 I have this same code working elsewhere in my app, biggest difference being this particular instance returns one row only, as opposed to multiple in the other places.
我在我的应用程序的其他地方都使用相同的代码,最大的不同是该特定实例仅返回一行,而在其他地方则返回多行。
When I manually execute the script I can see this JSON output: 当我手动执行脚本时,可以看到以下JSON输出:
[{"total_energy":"34011.920000","earliest_install_date":"2012-01-01"}]
When I execute the code below, the data array is empty / undefined. 当我执行以下代码时,数据数组为空/未定义。 If I change the ".getJSON" to ".get" I can now see the values in data but I still cannot access them.
如果将“ .getJSON”更改为“ .get”,现在可以看到数据中的值,但仍然无法访问它们。 I have tried via
data.total_energy
but I get "undefined". 我已经尝试通过
data.total_energy
但我得到“未定义”。 Any help is appreciated. 任何帮助表示赞赏。
The Javascript code: Javascript代码:
jQuery.getJSON(url, function(data) {
console.log("Earliest Date= " + data.earliest_install_date);
console.log("Total Energy= " + data.total_energy);
})
.done(function() {
})
.fail(function(jqxhr, textStatus, error ) {
var sysError = textStatus + ", " + error;
showPopupMsg(errorClass, logoutFlag, "There was an error retrieving the Environmental Savings data.<br/>If the issue persists please contact SMA for support...<br/>Error: " + sysError);
})
.always(function() {
});
The result in the console is: 控制台中的结果是:
Earliest Date= undefined
Total Energy= undefined
Your JSON is an array: 您的JSON是一个数组:
[{"total_energy":"34011.920000","earliest_install_date":"2012-01-01"}]
You need to access the first element of the array returned like so: 您需要像这样访问返回的数组的第一个元素:
jQuery.getJSON(url, function(data) {
console.log("Earliest Date= " + data[0].earliest_install_date);
console.log("Total Energy= " + data[0].total_energy);
})
.done(function() {
})
.fail(function(jqxhr, textStatus, error ) {
var sysError = textStatus + ", " + error;
showPopupMsg(errorClass, logoutFlag, "There was an error retrieving the Environmental Savings data.<br/>If the issue persists please contact SMA for support...<br/>Error: " + sysError);
})
.always(function() {
});
Try this: 尝试这个:
jQuery.getJSON(url, {}).done(function(data) { console.log("Earliest Date= " + data.earliest_install_date); console.log("Total Energy= " + data.total_energy); }) .fail(function(jqxhr, textStatus, error ) { var sysError = textStatus + ", " + error; showPopupMsg(errorClass, logoutFlag, "There was an error retrieving the Environmental Savings data.
If the issue persists please contact SMA for support...
Error: " + sysError); }) .always(function() { });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.