使用JSON对象的值填充输入字段 [英] Populating input fields with values from JSON object

查看:83
本文介绍了使用JSON对象的值填充输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试使用从mysql数据库获取的值填充表单。由于jquery的帮助,表单非常动态。单击按钮可以添加或删除输入字段。 有关表单结构的更多背景信息,请查看我之前的。我在使用数据库中的值填充此表单时遇到了困难。我有foreach循环,它获取值并将它们放在JSON对象中。如何使用这些值自动填充字段? JSFIDDLE

I am currently trying to populate a form with values fetched from mysql database. The form is very dynamic thanks to the help of 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. How can autopolulate the fields with these values? JSFIDDLE

编辑 - 我是意识到存在角度,余烬,淘汰赛和其他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

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和JSON

  • SCRIPT元素和JSONP

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

After that you have to parse the data and build the HTML DOM elements you need. This can be done with templates or with DOM functions. When the code grows, you have to create many js classes to do different parts of the job. You can use for example MVC or MVVM pattern as well...

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

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...

编辑:

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

In this exact case you should use the jquery ajax function the get and unserialize your json from your php file. After that you have to write a parser for that json which can transform it to "thing" instances. In your case the easiest way to modify the addItem() function to accept a json parameter.

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

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这不是完美的,要解析树,你必须准备你的 addItem ()用递归解析项目的函数。我想你可以自己做...

Ofc this is not perfect, to parse tree you have to prepare your addItem() function to parse items with recursion. I guess you can do that yourself...

这篇关于使用JSON对象的值填充输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆