2009-10-21 94 views
0

我在jQuery中解析JSON,并遇到了麻烦。我想检查JSON对象中'time'的值。这里是我的审判职能:使用jQuery解析JSON时遇到问题

$.ajax({ 
    url: 'do_chat.php5', 
    type: 'post', 
    data: ({'message':'','poster':poster,'logged_in':logged_in}), 
    dataType: 'json', 
    success: function(data) { 
     $.each(data, function(interval, message) { 
     if(message['time']) { 
    $('#chatWindow').append('<p>hi</p>'); 
     } 
}); 
    } 
    }); 

从我的服务器返回的字符串看起来像:

{“大字报”:“”,“消息”:“没有消息”,“时间”:1256084677 }

我不确定$ .each的语法。我正在使用PHP来编码JSON字符串,该字符串作为一个php assoc数组开始。我相信我的错误很多,任何帮助都非常感谢!

编辑:后续问题 - 如何让PHP生成一个JSON数组?目前,我用它来生成单个对象:

$messages = mysqli_fetch_assoc($new_res); 
$msg = $messages["content"]; 
$who = $messages["poster"]; 
$time = $messages["time_added"]; 
$message = array(
    'poster' => $who, 
    'message' => $msg, 
    'time' => $time 
); 

echo json_encode($message); 

但如果我从我的数据库查询得到多行,我该怎么做呢?

+0

你有什么错误? – gn22 2009-10-21 00:33:58

回答

2

您的代码存在的问题是您要返回单个JSON对象{"poster":"","message":"No messages!","time":1256084677},但您随后使用$.each来遍历它。

$.each需要一个数组,因为您没有返回数组,所以$.each会循环遍历JSON对象的元素。

要解决你的代码,你需要要么确保你的服务器返回一个数组,如: [{"poster":"","message":"No messages!","time":1256084677}]

取出$.each,让你有:

$.ajax({ 
    url: 'do_chat.php5', 
    type: 'post', 
    data: ({'message':'','poster':poster,'logged_in':logged_in}), 
    dataType: 'json', 
    success: function(data) { 
     if(data['time']) { 
      $('#chatWindow').append('<p>hi</p>'); 
     } 
    } 
}); 
0
$.ajax({ 
    url: 'do_chat.php5', 
    type: 'post', 
    data: ({'message':'','poster':poster,'logged_in':logged_in}), 
    dataType: 'json', 
    success: function(data) { 
     if (typeof data.time != 'undefined') { 
      $('#chatWindow').append('<p>' + data.poster + ' - ' + data.message + '</p>'); 
     } 
    }); 
}); 
0

我结束了使用JSON解析器http://json.org

$.ajax({ 
    type: "POST", 
    url: "getData.asmx/retrieveSubcontractorList", 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    data: "{}", 
    success: function(result2) { 
     var toolsData = JSON.parse(result2.d); 

诀窍是,该数据实际上是在一个名为d属性。