无法在ajax中读取未定义的属性“长度”

I try to get the number of object within an array but I got 'length' of undefined.

My js

..
      success: function(data){
        console.log(data.item.length);
      },

My PHP

<?php
   $arr = array();
   $arr["item"]["book"] = "harry porter";
   $arr["item"]["available"] = true;

   echo json_encode($arr);
?>

output

{"item":{"book":"harry porter","available":true}}

All content sent via HTTP(S) requests are received as strings (in Ajax, at least). When you receive a string that's in JavaScript's Object format, it's called JSON. You need to parse this JSON back into a readable JavaScript object.

You would need to use the JSON.parse function, this turns JSON into a JavaScript Object. Also .length only works on arrays not on object so you need to use console.log(Object.keys(data).length);

Your function would look like:

data=JSON.parse(data);
console.log(Object.keys(data).length);

data = {"item":{"book":"harry porter","available":true}};
alert(Object.keys(data.item).length);

</div>

You have to parse the JSON string to a JSON object before operating on it.

var obj = eval ("(" + data + ")");

BTW, I see that item is not an array. If you want to make it an array, it has to be like this

{item : [{"book" : "harry potter", "available" : true}, {..}]}

I try to get the number of object within an array

In the success callback you have got a js object and you want to get the number of objects inside it. so when you do data.item.length it goes to check the length of the js object which is not available for it.

Instead you have to check for the keys names of js object like item which is available in your callback data object. So the piece of code you are looking for is this:

Object.keys(data).length

this will count the keys name of {"item":{}}, so in your case you just have one (1).

var obj = {"item":{"book":"harry porter","available":true}};
alert(Object.keys(obj).length)

so in your success callback you can do this:

  success: function(data){
    console.log(Object.keys(data).length);
  },
</div>
alert(Object.keys(data).length); 

your code may like this

$.ajax({
url: "items.php",
type: "POST",
dataType: "JSON",
success: function(data) {
data=JSON.parse(data);
alert(Object.keys(data).length); 
});