创建和修改 json 字符串

这是我第一次使用 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) 的输出

http://img3.mukewang.com/643a6e250001a3fc04250169.jpg

获取数据.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}

我怎样才能意识到呢?


蓝山帝景
浏览 178回答 1
1回答

GCT1015

由于 chatData 是 JSON(字符串),您可以:解析成一个对象JSON.parse做出改变将其转换回字符串JSON.stringify// result from ajax call, jquery converts this from the php json to an object/arrayvar result = [{chatToken:"tgv5pxfjsDGXA3JcEYVM",lastMessageID:188}];// string from `var chatData = <?php ...` as JSONvar chatData = '{"tgv5pxfjsDGXA3JcEYVM":88,"a9gxNZ7HzfcJXQsWCtAp":99}';&nbsp;// convert string to objectvar data=JSON.parse(chatData);&nbsp;// use the first result array ([0]) chatToken to update chatDatadata[result[0].chatToken] = result[0].lastMessageID;// convert back to JSON (string)chatData = JSON.stringify(data);// show resultconsole.log(chatData);在你的情况下,我建议chatData在开始时转换为一个对象var&nbsp;chatData&nbsp;=&nbsp;JSON.parse('<?&nbsp;echo&nbsp;json_encode($chatData);&nbsp;?>');然后将其用作对象,然后仅在需要时转换为 json(string)(在 ajax 帖子中)data:&nbsp;'chatData='+JSON.stringify(chatData),
打开App,查看更多内容
随时随地看视频慕课网APP