2016-02-05 81 views
2

我正在使用AJAX自動刷新的聊天系統上工作。首先我使用jQuery $ .post函數,但是因爲我想從我的PHP腳本中返回JSON數據,所以我想使用$ .ajax函數。我的腳本運行良好使用$ .post函數,但我不能返回JSON。這是相關代碼: 的Javascript:AJAX調用發送JSON數據

$.ajax({ 
    url: "pages/loadmessage.php", 
    type: "POST", 
    data: {"c": getUrlParameter("c"), "t": messagetime}, 
    dataType: "json", 
    success: function(pData){ 
     console.log(pData); 
    }, 
    error: function(xhr, status, error) { 
     alert(error + status); 
    } 
}); 

PHP代碼:

<?php 
require_once("../init.php"); 
header('Content-Type: application/json'); 
if (Input::exists() && Input::get("c") && Input::get("t")) { 
    $chat = new Chat($user->data()->ID, Input::get("c")); 
    $messages = $chat->getNewMessages(Input::get("t"), $user->data()->ID); 
    if ($messages) { 
     $result = array(
      'topic' => $chat->getTopic(), 
      'messages' => array() 
     ); 
     foreach($messages as $m) { 
      array_push($result['messages'], array('source' => 'mine', 'Text' => $m->Text)); 
     } 
     echo json_encode("string!!!"); 
    } 
} else { 
    echo json_encode("string" . Input::get("c") . Input::get("t") . Input::exists()); 
} 
?> 

我已經嘗試設置AJAX調用 「應用/ JSON」 的contentType中,並使用數據轉換成JSON JSON.stringify,但沒有輸入數據到達PHP腳本。如果只有一個參數(數據:{「c」:getUrlParameter(「c」)})被髮送到PHP腳本,代碼就可以工作... 我已經搜索過StackOverflow,但我找不到解決方案...

由於

+0

您是否檢查了[$ .post](http://api.jquery.com/jquery.post/)的最後一個參數? – Jigar

+0

控制檯中的任何錯誤消息 –

+1

'$ .post'可以返回JSON,您只需使用正確的語法:'$ .post(「pages/loadmessage.php」,{「c」:getUrlParameter(「c」), 「t」:messagetime},function(pData){/ * do stuff * /},「json」);' –

回答

1

JSON例如:

的index.html

<script type="text/javascript"> 

    $.ajax({ 
     url: "out.php", 
     type: "POST", 
     data: {"param1": "test 1", "param2": "test2"}, 
     dataType: "json", 
     success: function(data){ 
      alert("param1:"+data.param1+" | param2:"+data.param2); 
     }, 
     error: function(xhr, status, error) { 
      alert(error + status); 
     } 
    }); 
</script> 

out.php

<?php 

    if(isset($_POST["param1"])){ $param1 = $_POST["param1"];} 
    if(isset($_POST["param2"])){ $param2 = $_POST["param2"];} 

    $out = array("param1"=>$param1,"param2"=>$param2); 

    echo(json_encode($out)); 
?>