gpt4 book ai didi

javascript - 如何循环JSON上的所有数据

转载 作者:行者123 更新时间:2023-11-28 15:44:22 25 4
gpt4 key购买 nike

您好,我尝试循环 json_encode() 来获取根据我的查询相关的所有数据脚本工作正常,但循环部分不行

这是我到目前为止所拥有的:

$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_GET['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}

$comb = $usern . $_GET['name'];


$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd;
$sql7 = "SELECT message_content, username , message_time, recipient FROM ".$tbpre."chat_conversation WHERE msgid=:chat";

$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();



$message_query = $stmt7;


if(count($message_query) > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
echo json_encode($message_array);
}
}

它只从我的数据库返回一项数据..

这是我的 javascript,用于从我的 php 端检索:

        function AjaxRetrieve()
{
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};

$.get('includes/getChat.php', data, function (result) {
var res = $([]);

$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});

$("#clog").html(res);

}, 'json');
}

最佳答案

您只需在每次循环迭代时继续覆盖 $json_string 即可。

您想要做的是将数据库数据保存到数组中然后进行编码。

$array = array();
if(count($message_query) > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
$array[] = $message_array;
}
}
$json_string = json_encode($array);
echo $json_string;

在您的 AJAX 成功处理函数中,您似乎没有正确迭代数组。

请注意,您仅对返回结果集的第一个数组元素调用 $.each():

$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});

我认为您会想要像这样迭代整个结果集:

$.each(result, function(rowKey, row) {
// row is single row of result set from database
// rowKey is numerical index of the row in the result set
// rowKey is probably not useful here
// You can just append new div to #clog with
// whatever content from row which you desire
// for example, this would insert message_content value
// in child div to #clog
$("#clog").append('<div>' + row.message_content + '</div>');
});

关于javascript - 如何循环JSON上的所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22830006/

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