简体   繁体   English

使用JSON对象的值填充输入字段

[英]Populating input fields with values from JSON object

I am currently trying to populate a form with values fetched from mysql database. 我目前正在尝试使用从mysql数据库获取的值填充表单。 The form is very dynamic thanks to the help of jquery. 由于jquery的帮助,表单非常动态。 Input fields can be added or deleted with a button click. 单击按钮可以添加或删除输入字段。 For more background information in the structure of the form check my previous . 有关表单结构的更多背景信息,请查看我之前的信息 I am running into difficulties in a way to populate this form with values from the database. 我在使用数据库中的值填充此表单时遇到了困难。 I have foreach loop that fetches the values and places them in a JSON object. 我有foreach循环,它获取值并将它们放在JSON对象中。 How can autopolulate the fields with these values? 如何使用这些值自动填充字段? JSFIDDLE 的jsfiddle

Edit- I am aware there exists angular, ember, knockout and other js technologies for the job but for learning reasons I decided to this without the help of a commercial framework. 编辑 - 我知道存在角度,余烬,淘汰赛和其他js技术,但出于学习的原因,我决定在没有商业框架的帮助下实现这一目标。

Form 形成

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

You have to deliver your data - generated by the server - to your client. 您必须将您的数据(由服务器生成)提供给您的客户。

2 popular ways I can recommend: 我推荐的两种流行方式:

  • AJAX and JSON AJAX和JSON
  • SCRIPT element and JSONP SCRIPT元素和JSONP

After that you have to parse the data and build the HTML DOM elements you need. 之后,您必须解析数据并构建所需的HTML DOM元素。 This can be done with templates or with DOM functions. 这可以使用模板或DOM函数完成。 When the code grows, you have to create many js classes to do different parts of the job. 当代码增长时,您必须创建许多js类来完成作业的不同部分。 You can use for example MVC or MVVM pattern as well... 你可以使用例如MVC或MVVM模式......

After a long time you'll have your own client side framework, like angular, backbone, ember, etc... It does worth to use them I think, but it is your choice... 经过很长一段时间,你将拥有自己的客户端框架,如角度,骨干,余烬等......我认为值得使用它们,但这是你的选择......

edit: 编辑:

In this exact case you should use the jquery ajax function the get and unserialize your json from your php file. 在这种情况下,您应该使用jquery ajax函数从您的php文件中获取和反序列化您的json。 After that you have to write a parser for that json which can transform it to "thing" instances. 之后,你必须为该json编写一个解析器,它可以将其转换为“thing”实例。 In your case the easiest way to modify the addItem() function to accept a json parameter. 在您的情况下,修改addItem()函数以接受json参数的最简单方法。

For example the modifications by a simple item array should be something like this: 例如,简单项数组的修改应该是这样的:

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

Ofc this is not perfect, to parse tree you have to prepare your addItem() function to parse items with recursion. Ofc这不是完美的,要解析树,你必须准备你的addItem()函数来解析带递归的项目。 I guess you can do that yourself... 我想你可以自己做...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM