javascript - 检索 JSON 结果

标签 javascript php json

您好,我使用了一个聊天应用程序教程中的代码片段,它的所有脚本都工作正常,但在我调整它以使代码根据我的要求工作后,几乎所有脚本都在工作,除了检索对话

我遇到的错误是它没有从我的数据库中检索对话

这是修改后的脚本

 //Create the JSON response.
$json = '{"messages": {';
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {

    $json .= '"message":[ {';
    $json .= '"id":  "0",
                "user": "Admin",
                "text": "You are not currently in a chat session.  <a href="">Enter a chat session here</a>",
                "time": "' . date('h:i') . '"
            }]';
} else {
    $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',$_POST['rid'], PDO::PARAM_STR);
    $stmt6->execute();
        foreach($stmt6->fetchAll()as $res)
            {
                $usern = $res['username'];
                $user_lvl = $res['ulvl'];
            }

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

      //Validation if msgid exists before creating a new table on the 2nd database
      $sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
      $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 . "chat_conversation";
    $sql7 = "SELECT msgid, message_content, username , message_time FROM $tblpre WHERE msgid=:chat";

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

    $message_query = $stmt7;
    //Loop through each message and create an XML message node for each.
    if(count($message_query) > 0) {
        $json .= '"message":[ ';    
        while($message_array = $stmt7->fetch(PDO::FETCH_ASSOC)) {
            $json .= '{';
            $json .= '"id":  "' . $message_array['msgid'] . '",
                        "user": "' . htmlspecialchars($message_array['username']) . '",
                        "text": "' . htmlspecialchars($message_array['message_content']) . '",
                        "time": "' . $message_array['message_time'] . '"
                    },';
        }
        $json .= ']';
    } else {
        //Send an empty message to avoid a Javascript error when we check for message lenght in the loop.
        $json .= '"message":[]';
    }

}

//Close our response

$json .= '}}';
echo $json;

这里是调用这个脚本的代码

    //Gets the current messages from the server
        function getChatText() {
            if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
                receiveReq.open("GET", 'includes/getChat.php?chat='+uid+'&last=' + lastMessage, true);
                receiveReq.onreadystatechange = handleReceiveChat; 
                receiveReq.send(null);
            }           
        }
        function sendChatText() {

            if (sendReq.readyState == 4 || sendReq.readyState == 0) {
                sendReq.open("POST", 'includes/getChat.php?last=' + lastMessage, true);
                sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                sendReq.onreadystatechange = handleSendChat; 
                var param = 'message=' + document.getElementById('txtA').value;
                param += '&name='+user;
                param += '&uid='+uid;
                param += '&rid='+document.getElementById('trg').value;
                sendReq.send(param);
                document.getElementById('txtA').value = '';
            }                           
        }
    //When our message has been sent, update our page.
        function handleSendChat() {
            //Clear out the existing timer so we don't have 
            //multiple timer instances running.
            clearInterval(mTimer);
            getChatText();

        }
        function handleReceiveChat() {
            if (receiveReq.readyState == 4) {
                //Get a reference to our chat container div for easy access
                var chat_div = document.getElementById('clog');


                var response = eval("(" + receiveReq.responseText + ")");
                for(i=0;i < response.messages.message.length; i++) {
                    chat_div.innerHTML += response.messages.message[i].user;
                    chat_div.innerHTML += '&nbsp;&nbsp;<font class="chat_time">' +  response.messages.message[i].time + '</font><br />';
                    chat_div.innerHTML += response.messages.message[i].text + '<br />';
                    chat_div.scrollTop = chat_div.scrollHeight;
                    lastMessage = response.messages.message[i].id;
                }
                mTimer = setTimeout('getChatText();',20000); //Refresh our chat in 2 seconds
            }
        }

我是不是遗漏了什么或做错了什么?

最佳答案

您应该使用 json_encode 重写:

$messages = array();
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
    $message_object = (object) array(
        "id"=>"0",
        "user"=>"Admin",
        "text"=>"You are not currently in a chat session.  &lt;a href=\"\"&gt;Enter a chat session here&lt;/a&gt;",
        "time"=>date('h:i')
    );
    $messages[] = (object) array("message"=>$message_object);
} else {
    $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',$_POST['rid'], PDO::PARAM_STR);
    $stmt6->execute();
        foreach($stmt6->fetchAll()as $res)
            {
                $usern = $res['username'];
                $user_lvl = $res['ulvl'];
            }

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

    //Validation if msgid exists before creating a new table on the 2nd database
    $sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
    $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 . "chat_conversation";
    $sql7 = "SELECT msgid, message_content, username , message_time FROM $tblpre WHERE msgid=:chat";

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

    $message_query = $stmt7;
    //Loop through each message and create an XML message node for each.
    if(count($message_query) > 0) {
        $message_object = (object) array(
            "id"=>$message_array['msgid'],
            "user"=>htmlspecialchars($message_array['username']),
            "text"=>htmlspecialchars($message_array['message_content']),
            "time"=>$message_array['message_time'
        );
        $messages[] = (object) array("message"=>$message_object);
    } else {
        //Send an empty message to avoid a Javascript error when we check for message lenght in the loop.
        $messages[] = (object) array("message"=>array());
    }

}

//Close our response
$result = (object) array('messages'=>$messages);
$json = json_encode($result);
echo $json;

关于javascript - 检索 JSON 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22826284/

相关文章:

php - 存储库模式与 ORM

php - MySQL 根据最后发送的消息排序用户列表

php - 无法正确读取 csv(制表符分隔)

javascript - : mean in jquery? 是什么意思

javascript - 处理 jQuery.noConflict

javascript - 对象 JavaScript,无法读取未定义的属性...之前已读取

java - JsonNode isTextual() 莫名其妙地返回 false

php - 同步网络服务方法论或论文

json - Golang 解码/解码 JSON 中的无效 unicode

javascript - 如果返回 false,则设置下拉列表中先前选择的值