我从服务器收到了一个JSON对象,我希望它循环遍历所有返回的值,并填充两个动态创建的输入文本字段。
目前我已经返回了2条记录,但它只填充了一组字段,而另一组虽然已创建但仍未填充。 console.log
输出显示有两条记录:
0 Object {emailAdd: "bob@work.com", emailDesc: "work"}
1 Object {emailAdd: "john@home.com", emailDesc: "home"}
这是Jquery:
var emails = {% raw json_encode(emails) %};
$.each(emails, function(k,v) {
x = 1;
z = x++;
$('<input type="email" placeholder="Email" value="" id="email'+x+'" data-name="emailAdd" /><input type="text" placeholder="Description" value="" id="email'+z+'" data-name="emailDesc"/>').appendTo('#email');
$('#email' + x + '').val(v.emailAdd);
$('#email' + z + '').val(v.emailDesc);
x++;
console.log(k, v);
});
它似乎只是返回最后一条记录,而不是所有记录。如何显示所有返回的记录?
答案 0 :(得分:4)
您正在每x
次迭代初始化var each
。你可以试试这个:
var emails = {% raw json_encode(emails) %};
x=1;
$.each(emails, function(k,v) {
z=x++;
$('<div class="form-group1" name ="email" id="email"><input type="email" class="form-control" placeholder="Email" value="" id="email'+x+'" data-name="emailAdd" /><br><input type="text" class="form-control" placeholder="Description" value="" id="email'+z+'" data-name="emailDesc"/></div>').appendTo('#email');
$('#email'+x+'').val(v.emailAdd);
$('#email'+z+'').val(v.emailDesc);
x++;
console.log(k,v);
});
答案 1 :(得分:1)
试试这个
emails = JSON.parse('{% raw json_encode(emails) %}'); // or use $.parseJSON()
$.each(emails, function(k,v) {
// code goes here
console.log(k,v);
});
答案 2 :(得分:1)
您的代码会覆盖以前的值,因为您在每个循环中开始计算x=1
。以下内容应显示所有数据:
var emails = {% raw json_encode(emails) %};
$.each(emails, function(k,v) {
$('<div class="form-group1" name ="email" id="email"><input type="email" class="form-control" placeholder="Email" value="" id="email' + k + '-0" data-name="emailAdd" /><br><input type="text" class="form-control" placeholder="Description" value="" id="email' + z + '-1" data-name="emailDesc"/></div>').appendTo('#email');
$('#email'+k+'-0').val(v.emailAdd);
$('#email'+k+'-1').val(v.emailDesc);
console.log(k,v);
});