这是我第一次使用 json。是这样的情况:
我通过 php 从我的 mysql 数据库获取数据并将其存储到 php 数组中:
$statement = $mysqli->prepare("SELECT chatToken, lastMessageID FROM chat")
$statement->execute();
$result = $statement->get_result();
while($row = $result->fetch_object()) {
$chatData[$row->chatToken] = $row->lastMessageID;
}
现在我想在 jquery 函数中得到它:
我试过这个:
var chatData = '<? echo json_encode($chatData); ?>'
myFunction(chatData)
function myFunction(chatData) {
console.log(chatData)
// OUTPUT: {"tgv5pxfjsDGXA3JcEYVM":88,"a9gxNZ7HzfcJXQsWCtAp":99}
$.ajax({
type: "POST",
url: "getData.php",
data: 'chatData='+chatData,
dataType: 'json',
}).done(function(result) {
console.log(result);
// Please look the Picture below for output
})
}
console.log(result) 的输出
获取数据.php
<?php
$chatData = json_decode($_POST['chatData']);
$message = array();
foreach($chatData AS $chatToken => $lastMessageID) {
$statement = $mysqli->prepare("SELECT * FROM `messages` WHERE `chatToken` = ? AND `ID` > ?")
$statement->bind_param("ss", $chatToken, $lastMessageID);
$statement->execute();
$result = $statement->get_result();
while($row = $result->fetch_object()) {
$message[] = array(
"lastMessageID" => $row->ID,
"chatToken" => $row->chatToken,
);
}
$statement->close();
}
echo json_encode($message);
?>
到目前为止,一切都很好。但现在我想替换/更新我的var chatData:
{"tgv5pxfjsDGXA3JcEYVM":88,"a9gxNZ7HzfcJXQsWCtAp":99}
的值来自result. 最后它必须是:
{"tgv5pxfjsDGXA3JcEYVM":188,"a9gxNZ7HzfcJXQsWCtAp":99}
我怎样才能意识到呢?
GCT1015