weixin_33736832 2015-05-04 09:09 采纳率: 0%
浏览 10

jQuery JSON请求

I'm trying to send an AJAX request to a php file, and I want the php file to respond with a JSON object, however the AJAX function is continually failing when declare that I specifically want JSON returned. Any help will greatly be appreciated.

this is my ajax function

function getMessages(){
  $.ajax({
    type: 'POST',
    url: 'viewInbox',
    dataType: 'json',
    success: function(msg){
      //var content = data.substr(0, data.indexOf('<')); 
      populateMessages(msg);
    },
    error: function(){
      alert("ERROR");
    }
  });
}

and this is the relevant code for the php file

$message_links[] = array();
.....
while($run_message = mysql_fetch_array($message_query)){
    $from_id = $run_message['from_id'];
    $message = $run_message['message'];
    $user_query = mysql_query("SELECT user_name FROM accounts WHERE id=$from_id");
    $run_user = mysql_fetch_array($user_query);
    $from_username = $run_user['user_name'];
    $message_links[] = array("Hash" => "{$hash}", "From" => "{$from_username}", "Message" => "{$message}");
    // is that not valid json notation???
    }            
}
echo json_encode( $message_links, JSON_FORCE_OBJECT);
//$arr = array("a" => "1", "b" => "2");
//echo json_encode($arr);

UPDATE:

Well, I ended up switching the dataType request to 'html' and I am now able to actually access these values via JSON, however, I would still like to know why the php file was not returning correct JSON notation. Any insight would be awesome, cheers.

function getMessages(){
    $.ajax({
        type: 'POST',
        url: 'viewInbox',
        dataType: 'html',
        success:function(msg){
            var content = msg.substr(0, msg.indexOf('<'));
            msg = JSON.parse(content);
           populateMessages(msg);
        },
        error: function(xhr, textStatus, errorThrown) {
            alert(errorThrown);
            alert(textStatus);
            alert(xhr);
        }
    });
}
function populateMessages(data){
    var out = '';
    var json;
    for (var i in data){
        var my_string = JSON.stringify(data[i],null,0);
        json = JSON.parse(my_string);
        alert(json.Hash);
        out += i + ': ' + my_string  + '
';
    }
    alert(out);
}
  • 写回答

1条回答 默认 最新

  • YaoRaoLov 2015-05-04 10:08
    关注

    You need to set the header as json type before your echo in PHP:

    header('Content-Type: application/json');
    
    评论

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛