weixin_33721344 2015-11-26 18: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-26 18:40
    关注

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

    评论
  • weixin_33724570 2015-11-26 18:52
    关注

    When using contentType: 'application/json' you will not be able to rely on $_POST being populated. $_POST is only populated for form-encoded content types.

     $.ajax({
      url: "/pages/core.chat.php",
      type: "POST",
      dataType: "json",
      contentType:"application/x-www-form-urlencoded",
      data: {'action' : 'loadChat'},
    
      success: function(resp) {
        $("#chatBody").html(resp.refreshChat);
     }
    
    });
    

    If you want to send contentType:application/json you should actually send JSON, which you are not doing.

    评论
  • 妄徒之命 2015-11-26 20:16
    关注

    I have met one question which is similar with yours.here's my answer.

    PHP have there ways to get POST data.

    1.$_POST,which is usually for form data

    2.$HTTP_RAW_POST_DATA,if you can't get data from $_POST,try this one.

    3.$raw_post_data =file_get_contents('php://input', 'r'); basically the same as $HTTP_RAW_POST_DATA,but more effective.

    评论
  • weixin_33693070 2015-11-26 20:29
    关注

    There is no problem with your parameters dataType and data, the problem is with the contentType: "application/json", if you are using Chrome Dev Tools or something similar to check the server response, you should see something like this:

    <br />
    <b>Notice</b>:  Undefined index: action in <b>core.chat.php</b> on line <b>x</b><br />
    

    That's because core.chat.php is checking for a POST parameter and you are sending JSON.

    The PHP superglobal $_POST, only is supposed to wrap data that is either

    • application/x-www-form-urlencoded (standard content type for simple form-posts) or
    • multipart/form-data-encoded (mostly used for file uploads)

    Solution 1

    Send json and get the json data request via php://input changing your PHP code to receive JSON data instead of $_POST:

    in the ajax call change the data parameter:

    $.ajax({
      url: "/pages/core.chat.php",
      type: "POST",
      dataType: "json",
      contentType: "application/json",
      data: JSON.stringify({'action' : 'loadChat'}), //Send JSON
    
      success: function(resp) {
        $("#chatBody").html(resp.refreshChat);
     }
    
    });
    

    Change your PHP file to get json data and process it:

    $data = json_decode(file_get_contents('php://input'), true);
    if($data['action'] == 'loadChat')
       //do something
    

    Solution 2

    Remove contentType parameter from the Ajax call, by default is 'application/x-www-form-urlencoded; charset=UTF-8', and is what you would be expecting from the beginning.

    展开全部

    评论
  • weixin_33701294 2015-11-26 20:31
    关注

    Solution 1

    You can and should set the Content-Type header:

    <?php
    header('Content-Type: application/json');
    
    # Code ...
    
    if ($_POST['action'] == 'loadChat') {   
        $resp = array("refreshChat"=>$chat);
        echo json_encode($resp);
    }
    

    Otherwise, what are returning PHP is text only. More info: Returning JSON from a PHP Script

    The Content-type header is just used as info for your application. The browser doesn't care what it is. The browser just returns you the data from the AJAX call. If you want to parse it as JSON, you need to do that on your own.

    The header is there so your app can detect what data was returned and how it should handle it. You need to look at the header, and if it's application/json then parse it as JSON.

    This is actually how jQuery works. If you don't tell it what to do with the result, it uses the Content-type to detect what to do with it.

    -- Rocket Hazmat - HTTP Content-Type Header and JSON

    Solution 2

    Or we could fix it with:

    $.ajax({
        url: "/pages/core.chat.php",
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: {'action' : 'loadChat'},
    
        success: function(resp) {
            // JSON.parse solution
            resp = JSON.parse();
            $("#chatBody").html(resp.refreshChat);
        }
    
    });
    

    Documentation: JSON.parse

    展开全部

    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部