首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法遍历对象

无法遍历对象
EN

Stack Overflow用户
提问于 2014-03-29 02:05:09
回答 2查看 48关注 0票数 0

我正在使用jquery向服务器端发送一些值。作为回应,我要拿回字符串。然后,我使用JSON.parse()...when将其转换为一个对象--我正在查看控制台日志--在我看来,这个对象看起来很好。现在,当我试图遍历对象并试图检索值时,我无法遍历它。我不知道我在这里错过了什么。我在on change event..so上发送值,基本上,for循环每次都会在更改事件上运行

这是我的js

代码语言:javascript
复制
$(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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-03-29 02:07:52

尝试将代码放入回调中:

代码语言:javascript
复制
$.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
EN

Stack Overflow用户

发布于 2014-03-29 02:10:08

您不需要使用$.post解析json响应。注意,在文档(https://api.jquery.com/jQuery.post/)中有第四个参数dataType

例如:

代码语言:javascript
复制
$.post( "test.php", { func: "getNameAndTime" }, function( data ) {
  console.log( data.name ); // John
  console.log( data.time ); // 2pm
}, "json");

不需要解析它。

数据仅在成功回调中访问,如该示例所示。将您的循环移动到成功回调中。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22726096

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档