2014-03-29 96 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。你不需要自己解析它。 –