简体   繁体   中英

creating 2D javascript array from ajax php call

I have a mysql table with image data in.

I want to retrieve the image data and push into a javascript array.

There are two fields that I want to put into the array and they are image_ref, and image_name I know I need a 2D array for this and I need to retrive the data from the db using ajax and JSON.

I am not sure how to complete this.

I know I need to call the php page with a JSON ajax call

js:

var imagesArray[];

$.getJSON("get_image_data.php")
    .done(function(data) { 
  /*THIS IS WHERE I NEED HELP---*/
});         

get_image_data.php page

include("connect.php"); 
$query = mysql_query("SELECT * FROM images WHERE live='1' ORDER BY insertDate DESC");
while($row=mysql_fetch_array($query){
     echo json_encode(array("a" => $row['image_ref'], "b" => $row['image_name'])); 
}

I have highlighted where I need help in getting the returned data into the stockImages array.

Can anyone show me the light?

thanks in advance

By calling json_encode() multiple times in your loop, you are creating lots of singular bits of JSON. You should aim at creating and transmitting one transfer object, like this:

include("connect.php"); 
$query = mysql_query("SELECT * FROM images WHERE live='1' ORDER BY insertDate DESC");
$images = array(); 
while($row=mysql_fetch_array($query){
    $images[] = array("a" => $row['image_ref'], "b" => $row['image_name']); 
}
echo json_encode($images);

This will give you one JSON array, through which you can loop in your client side Javascript.

Actually, it is PHP that is wrong, 'cause on JS you will have the array you need directly in "data".

You PHP code should look like:

$query = mysql_query("SELECT * FROM images WHERE live='1' ORDER BY insertDate DESC");
$result = array();
while($row=mysql_fetch_array($query){
    $result[] = array("a" => $row['image_ref'], "b" => $row['image_name']); 
}
echo(json_encode($result));

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