【发布时间】:2014-02-27 09:29:25
【问题描述】:
我目前正在尝试使用从 mysql 数据库中获取的值填充表单。由于 jquery 的帮助,表单非常动态。通过单击按钮可以添加或删除输入字段。 For more background information in the structure of the form check my previous。我在用数据库中的值填充此表单的方式时遇到了困难。我有 foreach 循环,它获取值并将它们放在 JSON 对象中。如何使用这些值自动填充字段? JSFIDDLE
编辑 - 我知道有 angular、ember、knout 和其他 js 技术可以胜任这项工作,但出于学习原因,我决定在没有商业框架帮助的情况下这样做。
表格
<script type='text/template' data-template='item'>
<ul class="clonedSection">
<li style="list-style-type: none;">
<label>
<input class="main-item" data-bind = 'firstItem' type="checkbox" />First Item</label>
<ul class="sub-item" data-bind ='subItem' style="display: none;">
<li style="list-style-type: none;">
<label>
<input type="checkbox" />Sub Item</label>
</li>
</ul>
</li>
<li style="list-style-type: none;">
<label>
<input class="main-item" data-bind ='secondItem' type="checkbox" />Second Item</label>
<ul class="sub-item" style='display: none;' data-bind='detailsView'>
<li style="list-style-type: none;">How many items:
<select class="medium" data-bind ='numItems' required>
<option value="" selected>---Select---</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</li>
<li style="list-style-type: none;">
<div data-bind ='items'>
Item # {number}
<select>
<option value='initial' selected='true' >--- Select ---</option>
<option value='Bananas'>Bananas</option>
<option value='Apples'>Apples</option>
<option value='Oranges'>Oranges</option>
</select>
</div>
</li>
</ul>
</li>
</ul>
</script>
<input type='button' value='add' data-action='add' />
<input type='button' value='remove' data-action='remove' />
getItems.php
header("Content-type: application/json");
$db_select = $db_con->prepare("SELECT
p.firstItem,
p.subItem,
p.secondItem,
p.itemNames,
case itemNames when null then 0
when '' then 0
else
(LENGTH(itemNames) - LENGTH(replace(itemNames, ',', '')) +1)
end
as numItems
FROM items_list p
");
if (!$db_select) return false;
if (!$db_select->execute()) return false;
$results = $db_select->fetchAll(\PDO::FETCH_ASSOC);
// check that the 'id' matches up with a row in the databse
if(!empty($results))
$responses = array();
foreach ($results as $value){
$responses[] = array(
'firstItem' => ($value['firstItem'] == '1' ? true : false),
'subItem' => ($value['subItem'] == '1' ? true : false),
'secondItem' => ($value['secondItem'] == '1' ? true : false),
'numItems' => $value['numItems'],
'items' => array_map('trim', explode(',', $value['itemNames']))
);
}
echo json_encode($responses);
【问题讨论】:
-
查看 knockout.js。允许自动更新 DOM 的后端更改非常出色。
-
@RobRibeiro 虽然我建议自己在 cmets 中检查 Knockout(和其他此类 FW),并在另一个问题中我的答案内容 - 通常认为为这类事情提出框架有点不合适.注意 OP 已经有(手卷)数据绑定。 techAddict - 我会让其他人有机会从 PHP 方面提供更好的答案(至少我不是最好的 php 程序员),如果他们不这样做,我会尝试在几天:)
-
@BenjaminGruenbaum 好的,听起来不错。你能否在这里告诉我你的意思是迭代数组中的值 N 次,用它们创建 Thing 对象,然后迭代这些对象并在每个对象上调用 addThing。
-
同意罗布。不要试图重新发明轮子。看看 knockout、angular、ember 或其他 MV* 框架。这是应该在框架中的代码,您应该更加关注您的业务逻辑。
-
也可以使用handlebars,将json数据绑定到输入值属性。有很多方法可以做到这一点。
标签: javascript jquery