2013-03-10 87 views
0

我想將我的數組結果編碼爲json並將它們傳遞給javascript中的ajax成功事件。正確地編碼和解碼json結果(php到js)

PHP 

    $results = array(
     "time1" => 1, 
     "time2" => 2, 

    ); 
    echo json_encode($results); 

JAVASCRIPT/JQUERY

$.ajax({ 
      type: "POST", 
      url: "actions/myphp.php", 
      data: PassArray, 
      dataType: 'json', 
      beforeSend: function (html) { // this happens before actual call 
      // alert(html); 
      }, 
      success: function (html) { 
       // $("#loginoutcome").text(html); 
       // alert(html); 
       var obj = jQuery.parseJSON(html); 
       // Now the two will work 
       $.each(obj, function(key, value) { 
        alert(key + ' ' + value); 
       }); 

      }, 

離開JQUERY.parseJSON有拋出一個JSON解析意外的字符,我不認爲我說我需要它反正我在具體的數據類型指定:「JSON」,以上?.. 但是我怎麼才能檢索到的值?

感謝

回答

2

。當你穿過的數據類型爲JSON,jQuery將退給你JSON對象,你不必再解析它。

因此,使它像這樣:

success: function (obj) { 
      $.each(obj, function(key, value) { 
       alert(key + ' ' + value); 
      }); 

     }, 

如果你知道它的時間1或時間2,你可以這樣做:

success: function (obj) { 
      alert(obj.time1); 
      alert(obj.time2); 
     }, 
+0

謝謝,很好的答案,我有其他的問題,我有不止一個回聲,我只需要一個。 – Athanatos 2013-03-10 20:17:55