簡體   English   中英

jQuery.get從數據讀取值

[英]jQuery.get read values from data

我似乎無法從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 

您的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() {
});

嘗試這個:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM