简体   繁体   中英

ajax JSON call returning array of strings instead of objects

When I do the ajax call I am parsing the json_encoded data and when I log the data to the console it's actually an array of strings instead of objects. It's showing this.

[  
"{"   todoText":"dgdgdfgdfgdf",
"completed":false,
"editable":false
 }",

"{  
"todoText":"test 2",
"completed":false,
"editable":false
}",

"{  
"todoText":"test 3",
"completed":false,
"editable":false
}", 

"{  
"todoText":"sdfsdf",
"completed":false,
"editable":false
}"
]

This is the code I used to make the call to retrieve the data.

$(document).ready(function() {


$.get("php/listtasks.php", function(data){

var parsed = JSON.parse(data);


  $('#directions').html(parsed[0]);

  console.log(parsed);
})

});

This is the php code i used to encode the data and echo it back to the javascript.

$query  = "SELECT * FROM list";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);

$rows = $result->num_rows;


for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);


$x[$j] = $row[2];


}

echo json_encode($x);

Apparently, your $row[2] is a JSON object so you need to decode it like this:

$x[$j] = json_decode($row[2]);

I hope this will help you.

Replace

$x[$j] = $row[2];

With

$x[$j] = json_decode($row[2]);

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