这是我的PHP代码
<?php
session_start();
require_once __DIR__ . '/../../core/FbChatMock.php';
if (isset($_POST['id']))
{
$userId = (int) $_SESSION['user_id'];
$id = htmlentities($_POST['id'], ENT_NOQUOTES);
$chat = new FbChatMock();
$messages = $chat->getchat($userId, $id);
echo json_encode($messages);
}
$chat_converstaion = array();
$chat_converstaion[] = '<table>';
?>
我想将$ userId,$ id和$ messages这三个变量传递给json_encode函数,因为我已经传递了$ messages。这是我的javascript函数,我在使用这个json_encode
getMessage:function(ID) {
alert('function is at getMessage');
var that = this;
$.ajax({
url: '../forms/ajax/get_messages.php',
method:'post',
data: {id: ID},
success: function(data) {
alert(data);
var messages = JSON.parse(data);
for (var i = 0; i < messages.length; i++)
{
var msg = messages[i];
// alert (msg.message);
fbChat.addUserMessage('',msg.message);
}
// alert(data);
$('.msg_head').val('');
// that.getMessages();
}
});
},
addUserMessage:function (user, message)
{
msgBoxList = $('.msg_box').find('.msg_body');
msgBoxList.append("<div class='msg_a'>"+message+"</div>");
}
};
如何从PHP代码中将该变量转换为此javascript ajax调用?
答案 0 :(得分:1)
只需构建一个包含您希望传递的所有变量的数组,然后json_encode
:
<?php
session_start();
require_once __DIR__ . '/../../core/FbChatMock.php';
if (isset($_POST['id']))
{
$userId = (int) $_SESSION['user_id'];
$id = htmlentities($_POST['id'], ENT_NOQUOTES);
$chat = new FbChatMock();
$messages = $chat->getchat($userId, $id);
$return = array('userId' => $userId, 'id' => $id, 'chat' => $chat, 'messages' => $messages);
echo json_encode($return);
}
$chat_converstaion = array();
$chat_converstaion[] = '<table>';
?>
然后从JSON.parse
:
[...]
success: function(data) {
alert(data);
var json_data = JSON.parse(data);
var userId = json_data.userId;
var id = json_data.id;
var chat = json_data.chat;
var messages = json_data.messages;
[...]
答案 1 :(得分:0)
在PHP中进行少量修改:
NVL(V_ACTUAL_RESULT || '%', 'N/A')
和JS:
echo json_encode(['messages' => $messages, 'id' => $id, 'userId' => $userId]);