簡體   English   中英

使用JSON對象的值填充輸入字段

[英]Populating input fields with values from JSON object

我目前正在嘗試使用從mysql數據庫獲取的值填充表單。 由於jquery的幫助,表單非常動態。 單擊按鈕可以添加或刪除輸入字段。 有關表單結構的更多背景信息,請查看我之前的信息 我在使用數據庫中的值填充此表單時遇到了困難。 我有foreach循環,它獲取值並將它們放在JSON對象中。 如何使用這些值自動填充字段? 的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

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

您必須將您的數據(由服務器生成)提供給您的客戶。

我推薦的兩種流行方式:

  • AJAX和JSON
  • SCRIPT元素和JSONP

之后,您必須解析數據並構建所需的HTML DOM元素。 這可以使用模板或DOM函數完成。 當代碼增長時,您必須創建許多js類來完成作業的不同部分。 你可以使用例如MVC或MVVM模式......

經過很長一段時間,你將擁有自己的客戶端框架,如角度,骨干,余燼等......我認為值得使用它們,但這是你的選擇......

編輯:

在這種情況下,您應該使用jquery ajax函數從您的php文件中獲取和反序列化您的json。 之后,你必須為該json編寫一個解析器,它可以將其轉換為“thing”實例。 在您的情況下,修改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);
    }
});

Ofc這不是完美的,要解析樹,你必須准備你的addItem()函數來解析帶遞歸的項目。 我想你可以自己做...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM