我目前正在尝试使用从mysql数据库中提取的值来填充表单。由于jquery的帮助,表单非常动态。通过点击按钮可以添加或删除输入字段。 For more background information in the structure of the form check my previous。我遇到困难的方式是用数据库中的值填充此表单。我有foreach循环获取值并将它们放置在JSON对象中。如何使用这些值来自动调整字段? JSFIDDLE使用来自JSON对象的值填充输入字段
编辑 - 我知道存在的角度,烬,淘汰赛和其他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的后端更改是非常特殊的。 – azurelogic
@RobRibeiro虽然我在其他问题的答案的评论和内容中自己检查Knockout(和其他类似的FW),但通常认为在这种情况下建议一个框架是不恰当的。注意OP已具有(手动滚动)数据绑定。 techAddict - 我会让其他人有机会从PHP方面提供更好的答案(我不是最好的PHP程序员),如果他们不这样做,我会试着拿出一个答案几天:) –
@BenjaminGruenbaum好吧,听起来不错。你可以在这里向我展示你的意思吗?通过遍历数组中的值N次,用它们创建Thing对象,然后遍历这些对象并在它们中的每一个上调用addThing。 – techAddict82