2016-03-02 144 views
0

我試圖評估JSON響應,這裏是代碼 調用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 +」)「);」

請給我解決方案。 在此先感謝

回答

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)。看看我的例子,使用您自己的代碼:

//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(); 
?>