首页 > 解决方案 > 如何遍历 json 对象并作为选择表单字段选项插入 html 页面?

问题描述

在 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”选项。

标签: javascriptjqueryjsonajaxlaravel

解决方案


你很接近,将代码更改为:

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>'));
             });
         }
        }

推荐阅读