string(4) "3478" ["joindate"]=> string(19) "-6ren">
gpt4 book ai didi

javascript - 使用 PHP 数组制作数组 Javascript

转载 作者:行者123 更新时间:2023-11-28 13:14:03 24 4
gpt4 key购买 nike

我有一个 ajax 脚本,它返回一个关联数组列表,如下所示:

array(24) {  
["id"]=>
string(4) "3478"
["joindate"]=>
string(19) "2016-10-17 21:20:28"
["ip"]=>
string(12) "xxx.xxx.xx.xx"
...
}

array(24) {
["id"]=>
string(4) "3479"
["joindate"]=>
string(19) "2016-10-17 21:20:28"
["ip"]=>
string(12) "xxx.xxx.xx.xx"
...
}

HTML

<thead>
<tr>
<th><b><u>key 1</u></b></th>
<th><b><u>key 2</u></b></th>
<th><b><u>key 3</u></b></th>
<th><b><u>key 4</u></b></th>
<th><b>etc...</b></th>
</tr>
</thead>
<tbody>
<tr>
<td>value 1</td>
<td>value 2</td>
<td>value 3</td>
<td>value 4</td>
<td>etc...</td>
</tr>
<tr>
<td>value 1</td>
<td>value 2</td>
<td>value 3</td>
<td>value 4</td>
<td>etc...</td>
</tr>
</tbody>

我当前的JavaScript,其中formation是ID,methode是我的日期

data += "data=" +formation+' '+methode; 
$.ajax({
url: "core/display_lead.php",
type: "post",
data: data, dataType: "html",
success : function(code_html, statut){
console.log(code_html);
},
error : function(resultat, statut, erreur){
console.log("La requête n'a pas aboutie...");
console.log(resultat);
console.log(statut);
console.log(erreur);
}
});

如何获取创建表头的 key ,然后仅获取填充它的值?

目前我使用简单的 PHP var_dump 将数据传输到 Javascript,也许有一种更干净的方法?

非常感谢

最佳答案

因此,首先更改您的 PHP 代码以发回 JSON 响应而不是 var_dump

<?php

$all = array();
while ($row = mysql_fetch_array($req, MYSQLI_ASSOC)){
$all[] = $row;
}

echo json_encode($all);

现在在您的 javascript 中,告诉 .ajax 功能期望 JSON 作为响应

data += "data=" +formation+' '+methode; 
$.ajax({
url: "core/display_lead.php",
type: "post",
data: data,
dataType: "json", //<-- amended

success : function(data, statut){
console.log(data);
},
error : function(resultat, statut, erreur){
console.log("La requête n'a pas aboutie...");
console.log(resultat);
console.log(statut);
console.log(erreur);
}
});

现在使用这个和 @krasipenkov 答案并使用 javascript 调试器稍微查看一下数据,您应该几乎已经完成了。 success 方法上的 data 参数现在应该是 JavaScript native 数据类型,即数组或对象,具体取决于您在 PHP 中构建的数据,并且足够容易处理

Afraid I really have to add this as well now I see your using the mysql_extension. Every time you use the mysql_ database extension in new code a Kitten is strangled somewhere in the world it is deprecated and has been for years and is gone for ever in PHP7. If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions. Start here

关于javascript - 使用 PHP 数组制作数组 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40103266/

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