javascript - 通过 PHP json_encode 将三个变量传递给 javascript

标签 javascript php

这是我的 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 调用?

最佳答案

只需构建一个包含您希望传递的所有变量的数组,然后对其进行 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 构建 JS 变量:

[...]
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;
[...]

关于javascript - 通过 PHP json_encode 将三个变量传递给 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45190971/

相关文章:

php - 当 PHP 响应 header 包含 "application/json"时,JSON.parse 在 jQuery 中失败

php - laravel View 中的 e() 方法是做什么用的?

javascript - 将 jquery 'this' 和 'next' 更改为特定元素

php - 如何在 CakePHP 中制作或调用侧边栏

javascript - 如何在 grid-auto-flow :column stick to each other? 中制作自动放置 div

javascript - 单击移动设备的硬件按钮,它应该退出 TIZEN 应用程序

php - MySQL 加盟亏本

Javascript分配内存问题

javascript - JSON 对象多重过滤器

javascript - 如何从 URL 的哈希值中检索键值对