[英]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.