【问题标题】:How to loop through a json object and insert into html page as select form field options?如何遍历 json 对象并作为选择表单字段选项插入 html 页面?
【发布时间】:2019-10-31 15:31:19
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery json ajax laravel


    【解决方案1】:

    你已经接近了,把代码改成这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      • 1970-01-01
      • 2013-12-28
      • 2020-01-06
      相关资源
      最近更新 更多