简体   繁体   中英

jQuery Ajax Success get returned Array Length?

I'm trying to loop the returning Array from PHP . But jQuery .length is giving me:

'undefined'

PHP:

$items = array();
$items["country"] = "North Korea",
$items["fruits"] = array(
                      "apple"=>1.0,
                      "banana"=>1.2,
                      "cranberry"=>2.0,
                    );
echo json_encode( $fruits );

jQuery:

$.ajax({
    url: "items.php",
    async: false,
    type: "POST",
    dataType: "JSON",
    data: { "command" : "getItems" }
}).success(function( response ) {
    alert( response.fruits.apple );
    alert( response.length );
});
  • Here the First Alert() is ok, by returning: "1.0" .
  • Then the Second Alert() to detect length response.length is returning:
    • undefined

Then how can i loop this Array (or) how to loop the Fruits (defined by PHP like $items["fruits"] ) from jQuery end please?

simply try something like this

To do this in any ES5-compatible environment, such as Node, Chrome, IE 9+, FF 4+, or Safari 5+:

alert(Object.keys(response).length); 

your code

$.ajax({
    url: "items.php",
    async: false,
    type: "POST",
    dataType: "JSON",
    data: { "command" : "getItems" }
}).success(function( response ) {
    alert( response.fruits.apple );
    alert(Object.keys(response).length); 
});

REFERENCE

How to efficiently count the number of keys/properties of an object in JavaScript?

Looks like you're creating an associative array on the PHP side there, which pretty much comes in as an object in JavaScript. No .length property on objects.

You can "loop" over the object keys by either invoking Object.keys alongside Array.prototype.forEach or directly using a for..in loop.

That could look like

Object.keys( response ).forEach(function( key ) {
    console.log('key name: ', key);
    console.log('value: ', response[key]);
});

To do this you'll have to convert your object to something that has length, like so:

var length = Object.keys(response).length

Note this isn't a complete solution as it doesn't work in IE8.

Another solution is adding a "count" index to your JSON object in PHP, then reading that value in your JS like so:

$items["fruit_count"] = count( $fruits );

Based on your code you can use this to iterate through the keys

for(var fruitName in response.fruits)
    alert(fruitName + " => " + response.fruits[fruitName]))

However if you want to loop like a regular array, I suggest your PHP fruit object needs to be modified to something like the following

$items["fruits2"] = array(
              array("name" => "apple", "value"=>1.0),
              array("name" => "banana", "value"=>1.2),
              array("name" => "cranberry", "value"=>2.0),
            );

But then your Javascript will have to change to the following

alert( response.fruits2[0].value );
for(var i = 0; i < response.fruits2.length; i++)
    alert(response.fruits2[i].name + " => " + response.fruits2[i].value);

Convert response to array first

var data = Object.keys(response).map(function(_) { return response[_]; });

Then access the data length

data.length

As per the given code example, you are assigning array to $items["fruits"] variable and encodeing $fruits variable. Please encode the $items["fruits"] variable and check with your coding. After changing the variable its working fine for me.

Thanks,

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