【问题标题】:Populating input fields with values from JSON object使用来自 JSON 对象的值填充输入字段
【发布时间】: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


【解决方案1】:

您必须将您的数据(由服务器生成)交付给您的客户端。

我可以推荐的 2 种流行方式:

  • AJAX 和 JSON
  • SCRIPT 元素和 JSONP

之后,您必须解析数据并构建所需的 HTML DOM 元素。这可以通过模板或 DOM 函数来完成。当代码增长时,您必须创建许多 js 类来完成工作的不同部分。您也可以使用例如 MVC 或 MVVM 模式...

很长一段时间后,您将拥有自己的客户端框架,例如 angular、backbone、ember 等...我认为值得使用它们,但这是您的选择...

编辑:

在这种情况下,您应该使用jquery ajax 函数从您的php 文件中获取并反序列化您的json。 之后,您必须为该 json 编写一个解析器,该解析器可以将其转换为“事物”实例。在您的情况下,修改 addItem() 函数以接受 json 参数的最简单方法。

例如,一个简单的项目数组的修改应该是这样的:

function Thing(source) { //we use this as an object constructor.
    this.firstItem = false;
    this.subItem = false;
    this.secondItem = false;
    this.numItems = 0;
    this.items = []; // empty list of items
    if (source)
        this.merge(source);
}
Thing.prototype.merge = function (source){
    for (var property in source)
        if (source.hasOwnProperty(property))
            this[property] = source[property];
};
Thing.prototype.toJSON = function (source){
return ({
    firstItem: this.firstItem,
    subItem: this.subItem,
    secondItem: this.secondItem,
    numItems: this.numItems,
    items: this.items
}).toJSON();
};

function addItem(source) {
    var thing = new Thing(source); // get the data
    //...
}

function parseFormRepresentation(json){
    for (var i = 0, l=json.length; i<l; ++i)
        addItem(json[i]);
}

$.ajax({
    url: "getItems.php",
    success: function (data){
        parseFormRepresentation(data);
    }
});

这并不完美,要解析树,您必须准备 addItem() 函数以递归解析项目。我想你可以自己做......

【讨论】:

  • 感谢您的帮助,“解析树必须准备 addItem() 函数以递归解析项目”是什么意思?
  • 如果你的任何事物都可以有子事物,那么这个数据结构就叫做树。解析树比解析数组要难一些,但你可以快速学习它...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-14
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 2011-12-07
相关资源
最近更新 更多