我正在使用jquery向服务器端发送一些值。作为回应,我要拿回字符串。然后,我使用JSON.parse()...when将其转换为一个对象--我正在查看控制台日志--在我看来,这个对象看起来很好。现在,当我试图遍历对象并试图检索值时,我无法遍历它。我不知道我在这里错过了什么。我在on change 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
发布于 2014-03-29 02:07:52
尝试将代码放入回调中:
$.post("ajax.php", { categoryChoiceVal:categoryChoiceVal},function(data) {
x = $.parseJSON(data)
console.log(x);
$.each(x, function(){
html += this.address;
});
$('.dataContainer').html(html);
}); $.post是异步的。当您调用$.post时,来自服务器的响应尚未到达。通过放入回调,您可以确保在运行代码时响应已经到达。
发布于 2014-03-29 02:10:08
您不需要使用$.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");不需要解析它。
数据仅在成功回调中访问,如该示例所示。将您的循环移动到成功回调中。
https://stackoverflow.com/questions/22726096
复制相似问题