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');
    
    评论

报告相同问题?

悬赏问题

  • ¥20 家用射频美容仪技术规格
  • ¥25 matlab数值溢出该怎么解决?
  • ¥15 大家帮我看看为什么错了
  • ¥15 unity互动琴弦抖动效果
  • ¥15 做了个的二极管反向饱和电流测量电路,但是测试达不到效果
  • ¥15 nginx无证书访问https失败
  • ¥15 树莓派启动AP热点传入数据
  • ¥15 multisim中关于74ls192n和DSWPK开关的问题(相关搜索:计数器)
  • ¥15 在误装Windows server2019 后如何利用Windows.old恢复?
  • ¥20 代码实现状态连接包过滤防火墙的设计与实现