2009-10-21 36 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屬性。