我似乎无法从jQuery.getJSON访问返回的数据数组中的值,我无法理解为什么。我在我的应用程序的其他地方使用相同的代码,最大的区别是这个特定的实例只返回一行,而不是其他地方的多个。
当我手动执行脚本时,我可以看到这个JSON输出:
[{"total_energy":"34011.920000","earliest_install_date":"2012-01-01"}]
当我执行下面的代码时,数据数组为空/未定义。如果我将“.getJSON”更改为“.get”,我现在可以看到数据中的值,但我仍然无法访问它们。我试过通过data.total_energy
,但我得到了“未定义”。任何帮助表示赞赏。
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() {
});
控制台中的结果是:
Earliest Date= undefined
Total Energy= undefined
答案 0 :(得分:3)
您的JSON是一个数组:
[{"total_energy":"34011.920000","earliest_install_date":"2012-01-01"}]
您需要访问返回的数组的第一个元素,如下所示:
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() {
});
答案 1 :(得分:-1)
试试这个:
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() { });