无法评估json响应

时间:2016-03-02 11:08:07

标签: php json ajax

我正在尝试评估json响应,这是代码 调用json响应:

 <style type="text/css" media="screen">
            .chat_time {
                font-style: italic;
                font-size: 9px;
            }
        </style>
        <script language="JavaScript" type="text/javascript">

            var sendReqCon = getXmlHttpRequestObject();
            var receiveReqCon = getXmlHttpRequestObject();
            var lastMessageCon = 0;
            var mTimerCon;
            //Function for initializating the page.
            function startCon() {
                //Set the focus to the Message Box.
                document.getElementById('txt_context').focus();
                //Start Recieving Messages.
                getConText();

                              }     
            //Gets the browser specific XmlHttpRequest Object
            function getXmlHttpRequestObject() {
                if (window.XMLHttpRequest) {
                    return new XMLHttpRequest();
                } else if(window.ActiveXObject) {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                } else {
                    document.getElementById('p_status').innerHTML = 'Status: Cound not create XmlHttpRequest Object.  Consider upgrading your browser.';
                }
            }

            //Gets the current messages from the server
            function getConText() {
                if (receiveReqCon.readyState == 4 || receiveReqCon.readyState == 0) {                                    
                    receiveReqCon.open("GET", 'getCon.php?con=<?php echo $topic_id ?>&last=' + lastMessageCon, true);
                    receiveReqCon.onreadystatechange = handleReceiveCon; 
                    receiveReqCon.send(null);                                        
                }           
            }
            //Add a message to the chat server.
            function sendConText() {
                if(document.getElementById('txt_context').value == '') {
                    alert("You have not entered a context");
                    return;
                }
                if (sendReqCon.readyState == 4 || sendReqCon.readyState == 0) {
                    sendReqCon.open("POST", 'getCon.php?con=<?php echo $topic_id ?>&last=' + lastMessageCon, true);
                    sendReqCon.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                    sendReqCon.onreadystatechange = handleSendCon; 
                    var param = 'context=' + document.getElementById('txt_context').value;
                    param += '&namecon=<?php echo $user_name?>';
                    param += '&con=1';
                    param += '&uidcon=<?php echo $logged_user?>';
                    sendReqCon.send(param);
                    document.getElementById('txt_context').value = '';
                }                           
            }
            //When our message has been sent, update our page.
            function handleSendCon() {
                //Clear out the existing timer so we don't have 
                //multiple timer instances running.
                clearInterval(mTimerCon);
                getConText();
            }
            function handleReceiveCon() {                            
                if (receiveReqCon.readyState == 4) {                                    
                    //Get a reference to our chat container div for easy access
                    var con_div = document.getElementById('div_con');
//                                        con_div.innerHTML+='check this div';
                    //Get the AJAX response and run the JavaScript evaluation function
                    //on it to turn it into a useable object.  Notice since we are passing
                    //in the JSON value as a string we need to wrap it in parentheses
                                        con_div.innerHTML= 'receiveReqCon.responseXML';
                    var response = eval("(" + receiveReqCon.responseXML + ")");
                                        echo ('response');
                    for(i=0;i < response.cont.context.length; i++) {
                        con_div.innerHTML += '<b>'+response.cont.context[i].user+'</b>';
                        con_div.innerHTML += '&nbsp;&nbsp;<font class="chat_time" style="color:black;">' +  response.cont.context[i].time + '</font><br />';
//                      con_div.innerHTML += '<p style="color:black;">'+response.messages.context[i].text + '</p>';
                        con_div.innerHTML += 'hello';
                        con_div.scrollTop = chat_div.scrollHeight;
                        lastMessageCon = response.cont.context[i].id;
                    }
                    mTimerCon = setTimeout('getConText();',2000); //Refresh our chat in 2 seconds
                }
            }
            //This functions handles when the user presses enter.  Instead of submitting the form, we
            //send a new message to the server and return false.

//                                              
            function blockSubmit1() {
                sendConText();
                return false;
            }
            //This cleans out the database so we can start a new chat session.
            function resetCon() {
                if (sendReqCon.readyState == 4 || sendReqCon.readyState == 0) {
                    sendReqCon.open("POST", 'getCon.php?chat=1&last=' + lastMessageCon, true);
                    sendReqCon.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                    sendReqCon.onreadystatechange = handleResetChat; 
                    var param = 'action=reset';
                    sendReqCon.send(param);
                    document.getElementById('txt_context').value = '';
                }                           
            }
            //This function handles the response after the page has been refreshed.
            function handleResetCon() {
                document.getElementById('div_con').innerHTML = '';
                getConText();
            }   
        </script>

创建json响应:

        <?php

//Send some headers to keep the user's browser from caching the response.
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" ); 
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" ); 
header("Cache-Control: no-cache, must-revalidate" ); 
header("Pragma: no-cache" );
header("Content-Type: text/plain; charset=utf-8");

require('database.php');

//Check to see if a message was sent.
if(isset($_POST['context']) && $_POST['context'] != '') {
    $c_id=db_input($_GET['con']);
    $u_id=db_input($_POST['uidcon']);
    $u_name=db_input($_POST['namecon']);
    $msg=db_input($_POST['context']);
    $sql = "INSERT INTO context(topic_id,user_id,user_name,context,context_time, status) VALUES ('$c_id','$u_id','$u_name','$msg',now(),'1')";
    db_query($sql);
}
//Check to see if a reset request was sent.
if(isset($_POST['action']) && $_POST['action'] == 'reset') {
    $sql = "DELETE FROM message WHERE chat_id = " . db_input($_GET['chat']);
    db_query($sql);
}

//Create the JSON response.
$json = '{"cont": {';
//Check to ensure the user is in a chat room.
if(!isset($_GET['con'])) {
    $json .= '"context":[ {';
    $json .= '"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') . '"
            }]';
} 
else {
    $last = (isset($_GET['last']) && $_GET['last'] != '') ? $_GET['last'] : 0;
//  $sql = "SELECT message_id, user_name, message, date_format(post_time, '%h:%i %p') as post_time" . 
//      " FROM message WHERE chat_id = " . db_input($_GET['chat']) . " AND message_id > " . $last;
//  $sql = "SELECT context_id, user_name, context, date_format(context_time, '%h:%i %p') as context_time" . 
//      " FROM context WHERE topic_id = " . db_input($_GET['con']) . " AND context_id > " . $last;

    $sql = "SELECT context_id, user_name, context, date_format(context_time, '%h:%i %p') as context_time" . 
        " FROM context";
    $context_query = db_query($sql);
    //Loop through each message and create an XML message node for each.
    if(db_num_rows($context_query) > 0) {
        $json .= '"context":[ ';    
        while($context_array = db_fetch_array($context_query)) {
            $json .= '{';
            $json .= '"id":  "' . $context_array['context_id'] . '",
                        "user": "' . htmlspecialchars($context_array['user_name']) . '",
                        "text": "' . htmlspecialchars($context_array['context']) . '",
                        "time": "' . $context_array['context_time'] . '"
                    },';
        }
        $json .= ']';
    } else {
        //Send an empty message to avoid a Javascript error when we check for message lenght in the loop.
        $json .= '"context":[]';
    }
}
//Close our response
$json .= '}}';
echo $json;
?>    

我无法评估json响应,我认为符合“var response = eval(”(“+ receiveReqCon.responseXML +”)“);”

请建议我的解决方案。 提前致谢

1 个答案:

答案 0 :(得分:0)

首先看你应该替换

header("Content-Type: text/plain; charset=utf-8");

header("Content-Type: application/json; charset=utf-8");

此外,在JS中解码JSON的最简单方法是使用JSON.parse(json);函数。看一下这个例子:

var json_string = '{"result":true,"string":"test"}',
    json_obj = JSON.parse(json_string);

// Write in console / alert dialog
console.log(json_string.result); alert(json_string.result);

在服务器端,您不应该自己创建JSON对象。使用内置函数json_encode($array)的PHP。使用您自己的代码查看我的示例:

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

    $json_obj['cont']['context'][] = 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')
                                          )
    /*
    $json .= '"context":[ {';
    $json .= '"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') . '"
            }]';
    */
} else { /*you do the rest of the job here*/ }

// at the end of php script you write:
echo json_encode($json_obj, JSON_PRETTY_PRINT);
exit();
?>