[英]How to loop through a json object and insert into html page as select form field options?
在 Laravel 项目中工作,我尝试使用 javascript Ajax 更新表单选择字段选项,每次更改另一个选择字段值时。
我目前已将所有数据返回到我的视图中,并且可以在控制台日志中看到它。 我之前遇到过这个问题,我基本上无法理解如何使用 javascript 遍历 json 对象。 我目前只能获取返回的两个数据结果之一以显示为选择选项。
下面的代码来自我的控制器,它在发出 ajax 请求时获取数据,这就是我当前传回数据的方式。
$templates = DB::table('templates')->where("page_name", "=", $page)->get();
return response()->json([
'status' => true,
'templates' => $templates
]);
这就是数据在控制台中的显示方式。
{status: true, templates: Array(2)}
status: true
templates: Array(2)
0:
created_at: "2019-06-17 22:29:44"
css: "somecss"
html: "somehtml"
id: 1
page_name: "page-1"
template_name: "template-1"
updated_at: "2019-06-17 22:29:44"
__proto__: Object
1:
created_at: "2019-06-18 01:30:49"
css: "somecss"
html: "somehtml"
id: 3
page_name: "page-1"
template_name: "template-2"
updated_at: "2019-06-18 01:30:49"
__proto__: Object
length: 2
__proto__: Array(0)
__proto__: Object
最后,这就是我目前尝试使用 javascript/jquery 循环并显示该数据的方式。
success: function(data) {
if(data.status == true) {
$.each(data.templates, function(i, template) {
$('#template-select').html('<option value="' + template.template_name + '">' + template.template_name + '</option>');
});
}
}
当前只有“template-2”显示为选择选项,此时应该同时存在“template-1”和“template-2”选项。
你很接近,将代码更改为:
success: function(data) {
if(data.status == true) {
$.each(data.templates, function(i, template) {
$('#template-select').append($('<option value="' + template.template_name + '">' + template.template_name + '</option>'));
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.