weixin_33721344 2015-11-27 02:32 采纳率: 0%
浏览 35

无法读取json编码的数据

I'm working on a super simple chat php and jQuery ajax based, but I'm having a problem in displaying a json encoded string through the ajax callback function.

Here's the ajax request:

$.ajax({
  url: "/pages/core.chat.php",
  type: "POST",
  dataType: "json",
  contentType: "application/json",
  data: {'action' : 'loadChat'},

  success: function(resp) {
    $("#chatBody").html(resp.refreshChat);
 }

});

and this is from the .php file

if ($_POST['action'] == 'loadChat') {   
    $resp = array("refreshChat"=>$chat);
    echo json_encode($resp);
}

where $chat contains the message text. All I get is a blank page. Also, if I send the ajax request without the dataType and contentType parameters and run the callback without .refreshChat, it prints the json encoded string as it's meant to be {"refreshChat":"chatmessage"}, so maybe the problem lies in the way I'm passing those parameters? Just guessing. I'm quite new to jQuery ajax and I've checked, double checked and triple checked but I don't know what I'm doing wrong. Thanks to anyone that can make the magic.

  • 写回答

5条回答 默认 最新

  • weixin_33724659 2015-11-27 02:40
    关注

    using the header("Content-Type: application/json", true); in your PHP code to specify that the PHP is returning json could help

    评论

报告相同问题?