gpt4 book ai didi

php - 将数据从 php 传回 ajax

转载 作者:可可西里 更新时间:2023-11-01 12:30:24 30 4
gpt4 key购买 nike

我怎样才能将数据从 php 的然后行传回 ajax?

PHP

$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$result = mysql_query($query);

while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {

$url[]=$rec['pic_location'];
$name[]=$rec['name'];
$age[]=$rec['age'];
$gender[]=$rec['gender'];


}

echo json_encode($url);
echo json_encode($name);
echo json_encode($age);
echo json_encode($gender);

Ajax

$(".goButton").click(function() {
var dir = $(this).attr("id");
var imId = $(".theImage").attr("id");

$.ajax({
url: "viewnew.php",
dataType: "json",
data: {
current_image: imId,
direction : dir
},
success: function(ret){
console.log(ret);
var arr = ret;
alert("first image url: " + arr[0][0] + ", second image url: " + arr[0][1]); // This code isnt working
alert("first image Name: " + arr[1][0] + ", second image name: " + arr[1][1]);
$(".theImage").attr("src", arr[0]);
if ('prev' == dir) {
imId ++;
} else {
imId --;
}
$("#theImage").attr("id", imId);
}
});

});
});
</script>

我的问题是如何在此处显示值?警报消息显示“未定义”?

最佳答案

您可以按照这些思路做一些事情。

PHP

$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$res = mysql_query($query);

$pictures = array();
while ($row = mysql_fetch_array($res)) {
$picture = array(
"pic_location" => $row['pic_location'],
"name" => $row['name'],
"age" => $row['age'],
"gender" => $row['gender']
);
$pictures[] = $picture;
}

echo json_encode($pictures);

JS

...
$.ajax({
...
dataType: "json",
...
success: function(pictures){
$.each(pictures, function(idx, picture){
// picture.pic_location
// picture.name
// picture.age
// picture.gender
});
}
});
...

关于php - 将数据从 php 传回 ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10960471/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com