简体   繁体   中英

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. 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:

[{"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. I have tried via data.total_energy but I get "undefined". Any help is appreciated.

The Javascript code:

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:

[{"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, {})
        
        .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() { });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM