2014-03-29 99 views
0

我正在使用jquery post發送一些值給服務器端。作爲迴應,我收回字符串。然後,我正在使用它並通過使用JSON.parse()轉換成一個對象...當我在查看控制檯日誌時,我看到了對象,這對我來說看起來很好。現在當我試圖循環對象並試圖檢索值時,我無法遍歷它。我不知道我在這裏錯過了什麼。我上的變化上發送的值event..so基本for循環的變化事件無法循環訪問對象

這裏運行每次都是我的js

$(function(){ 
    var categoryChoiceVal = ''; 
    var x = []; 
    var html = ''; 
    $('select').change(function() { 
     categoryChoiceVal = $('.categoryChoice option:selected').text().replace(/ /g, '%20'); 
     $.post("ajax.php", { categoryChoiceVal:categoryChoiceVal},function(data) { 

      x = $.parseJSON(data) 
      console.log(x); 
     }); 
     $.each(x, function(){ 
      html += this.address; 
     }); 
     $('.dataContainer').html(html); 
    }); 

}); 

這裏是我做的這個頁面。 http://soumghosh.com/otherProjects/phpDataOperation/eventcCalendar/testOne.php

+0

同一問題每天要問十次。可能重複的[如何從AJAX調用返回響應?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – meagar

回答

0

嘗試把你的代碼在你的回調:

$.post("ajax.php", { categoryChoiceVal:categoryChoiceVal},function(data) { 
    x = $.parseJSON(data) 
    console.log(x); 

    $.each(x, function(){ 
      html += this.address; 
    }); 
    $('.dataContainer').html(html); 
}); 

$.post是非同步。當您撥打$.post時,服務器的響應尚未到達。通過放置回調函數,您可以確信在代碼運行時響應已經到達。

+0

@ Khanh- - 如果我這樣做,我會變得不確定 – soum

+0

@soum:什麼是'undefined'? –

+0

@ Khanh - 輸出未定義。你應該能夠從鏈接中看到它。如果你需要看到我的php代碼,請告訴我,我也可以分享它 – soum

1

你不需要使用$.post解析json響應。請注意,在文檔(https://api.jquery.com/jQuery.post/)中有第四個參數dataType

例如:

$.post("test.php", { func: "getNameAndTime" }, function(data) { 
    console.log(data.name); // John 
    console.log(data.time); // 2pm 
}, "json"); 

無需解析它。

數據僅在成功回調中訪問,如該示例中所示。將您的循環移至成功回調中。

+0

@ joe - 但我實際上是做這個服務器端 $ json = json_encode($ obj,JSON_PRETTY_PRINT); echo $ json; 這就是我轉換成對象的原因。我不應該像那樣接近它嗎? – soum

+0

JQuery會自動爲你解析json。你不需要自己解析它。 –