Javascript 如何循环通过json对象并将其作为选择表单字段选项插入html页面?

Javascript 如何循环通过json对象并将其作为选择表单字段选项插入html页面?,javascript,jquery,json,ajax,laravel,Javascript,Jquery,Json,Ajax,Laravel,在一个Laravel项目中,我尝试使用JavaScriptAjax来更新表单select fields选项,每次更改另一个select fields值时 我目前拥有返回到视图的所有数据,并且可以在控制台日志中看到这些数据。我以前遇到过这个问题,我基本上不知道如何用javascript循环json对象。我当前只能获取返回显示为选择选项的两个数据结果之一 下面的代码来自我的控制器,它在发出ajax请求时获取数据,这就是我当前传回数据的方式 $templates=DB::table'templates

在一个Laravel项目中,我尝试使用JavaScriptAjax来更新表单select fields选项,每次更改另一个select fields值时

我目前拥有返回到视图的所有数据,并且可以在控制台日志中看到这些数据。我以前遇到过这个问题,我基本上不知道如何用javascript循环json对象。我当前只能获取返回显示为选择选项的两个数据结果之一

下面的代码来自我的控制器,它在发出ajax请求时获取数据,这就是我当前传回数据的方式

$templates=DB::table'templates'->wherepage\u name,=,$page->get; 返回响应->json[ “状态”=>true, “模板”=>$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>'));
             });
         }
        }