gpt4 book ai didi

javascript - 如何对两个数组进行json编码并在ajax中使用它们

转载 作者:行者123 更新时间:2023-12-03 06:02:45 25 4
gpt4 key购买 nike

这就是我想要做的。我想检索具有特定引用号的所有名称和详细信息。所以我正在使用 while 循环。但我不知道如何对这些值进行 json 编码并检索它们,以便我可以在 ajax 中使用它们,以便显示它们。另一个问题是我已经有一个 json 编码数组,我也想检索这些值.所以我想使用 json 编码检索两个数组。这是代码-

$sql = "SELECT *  From (select * from tran ORDER BY id  DESC LIMIT 1) AS name  ORDER BY id LIMIT 1";
$result = mysqli_query($conn,$sql);
$rows1 = mysqli_fetch_assoc($result);

$master_ref_no = $rows['master_tran_ref'];
$sql = "SELECT * FROM stk WHERE tran_ref = '$ref_no'";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result)){
$name = $row['name'];
$tot = $row['tot'];
$data[] = ["pname" => $name,"ptot"=>$tot];//but i dont know how do i retrieve this and use it in ajax.
}

$response = ["success" => true, "date" => $rows1['date'], "v_no" => $rows1['v_no'], "types" => $rows1['v_type']]; // this is working perfectly fine.

header('Content-type: application/json');
echo json_encode($response);

这就是我在ajax中使用它在html表格中显示的方式-

$.ajax({
type: "POST",
url: "demopost.php",
data: formData,
success: function(response){
if (response.success) {
$('#datepreview').val(response.date);
$('#v_nopreview').val(response.v_no);
$('#typepreview').val(response.types);
$('#entrysavedmodal').modal('show');
} else {
alert("failure in");
}
},
error: function(){
alert("failure out");
}
});

所以请帮我解决如何对从 while 循环检索到的所有这些值进行 json 编码并将它们与其他数组一起包含在内,即响应并在 ajax 中使用它们。提前致谢。

最佳答案

JSON 数组也可以是多维的,因此您可以将 $data 数组粘贴到 $results 中并将其传递,如下所示:

$response = ["data" => $data, "success" => true, "date" => $rows1['date'], "v_no" => $rows1['v_no'], "types" => $rows1['v_type']];

那么你的输出将具有如下结构:

{
data: {
0: {
pname: value1
ptot: value2
},
1: {
pname: value3
ptot: value4
}
},
success: true,
//rest of values here
}

例如,要访问 value3,您的 jQuery 将如下所示

results.data.1.pname

然后,您可以循环 results.data 级别来获取所有 pname/ptot 对,或者在编码之前在 PHP 代码中对其进行重构。

关于javascript - 如何对两个数组进行json编码并在ajax中使用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39686403/

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