简体   繁体   English

从ajax php调用创建2D javascript数组

[英]creating 2D javascript array from ajax php call

I have a mysql table with image data in. 我有一个带有图像数据的mysql表。

I want to retrieve the image data and push into a javascript array. 我想检索图像数据并推入javascript数组。

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. 我想将两个字段放入数组中,它们是image_ref,而image_name我知道我需要一个2D数组,我需要使用ajax和JSON从数据库中检索数据。

I am not sure how to complete this. 我不知道如何完成这个。

I know I need to call the php page with a JSON ajax call 我知道我需要调用带有JSON ajax调用的php页面

js: JS:

var imagesArray[];

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

get_image_data.php page get_image_data.php页面

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. 我已经突出显示了在将返回的数据导入stockImages数组时需要帮助的地方。

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. 通过在循环中多次调用json_encode() ,您将创建大量奇异的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. 这将为您提供一个JSON数组,您可以通过它在您的客户端Javascript循环。

Actually, it is PHP that is wrong, 'cause on JS you will have the array you need directly in "data". 实际上,PHP是错误的,因为在JS上你将直接在“数据”中拥有你需要的数组。

You PHP code should look like: 您的PHP代码应如下所示:

$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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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