在Laravel项目中工作时,我尝试使用javascript Ajax来更新表单选择字段选项,每次更改另一个选择字段的值。
我目前已经将所有数据返回到我的视图中,并且可以在控制台日志中看到这些数据。我以前遇到过这个问题,我基本上不能理解如何用javascript遍历一个json对象。我当前只能获取返回的两个数据结果中的一个,并将其作为select选项显示。
下面的代码来自我的控制器,它在发出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“选项。
发布于 2019-06-18 11:49:04
您已关闭,请将代码更改为:
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>'));
});
}
}https://stackoverflow.com/questions/56641465
复制相似问题