【问题标题】:binding nested json object value to a form field将嵌套的 json 对象值绑定到表单字段
【发布时间】:2010-05-13 21:35:28
【问题描述】:

我正在构建一个动态表单来编辑 json 对象中的数据。首先,如果存在这样的事情,请告诉我。我宁愿不构建它,但我已经多次搜索工具并且只找到需要输入引号的树状结构。我很乐意将所有值都视为字符串。此编辑功能适用于最终用户,因此需要简单且不令人生畏。

到目前为止,我有生成嵌套表来表示 json 对象的代码。对于每个值,我都会显示一个表单字段。我想将表单字段绑定到关联的嵌套 json 值。如果我可以存储对 json 值的引用,我会为 json 对象树中的每个值构建一个引用数组。我还没有找到用 javascript 做到这一点的方法。

我最后的方法是在编辑完成后遍历表。我宁愿动态更新,但单次提交总比没有好。

有什么想法吗?

// the json in files nests only a few levels. Here is the format of a simple case,
{
 "researcherid_id":{
  "id_key":"researcherid_id",
  "description":"Use to retrieve bibliometric data",
  "url_template" :[
    {
      "name": "Author Detail",
      "url": "http://www.researcherid.com/rid/${key}"
    }
  ]         
 }
}

$.get('file.json',make_json_form);

function make_json_form(response) {

   dataset = $.secureEvalJSON(response);
   // iterate through the object and generate form field for string values.

}

// Then after the form is edited I want to display the raw updated json (then I want to save it but that is for another thread)

// now I iterate through the form and construct the json object
// I would rather have the dataset object var updated on focus out after each edit.

function show_json(form_id){
 var r = {};
 var el = document.getElementById(form_id);
 table_to_json(r,el,null);
 $('body').html(formattedJSON(r));
}

【问题讨论】:

  • 所以您想根据对象生成表单并将表单字段绑定到对象属性?对象结构如何? JSON 只是一种字符串表示形式,您会发现只处理 Javascript 对象会更容易,并在需要时最后序列化为 JSON。

标签: javascript json


【解决方案1】:

更简单的方法是接受表单提交并以 JSON 格式输出数据。这样就不需要绑定变量了。

【讨论】:

    【解决方案2】:

    解决方案已经到来。 JQuery 现在有用于数据绑定和模板的插件。

    http://www.borismoore.com/2010/09/introducing-jquery-templates-1-first.html http://api.jquery.com/jQuery.template/ http://api.jquery.com/category/plugins/data-link/

    【讨论】:

      【解决方案3】:

      还有另一个简单的模板引擎可以将 JSON 数据直接加载到表单中。请参阅http://plugins.jquery.com/project/loadJSON 插件。它的工作方式与 Jack 放在这里的类似,但它使用纯 HTML 作为模板。

      您可以在http://code.google.com/p/jquery-load-json/wiki/WorkingWithFormElements 上查看如何使用它的说明,并在http://jquery-load-json.googlecode.com/svn/trunk/edit.html?ID=17 上查看现场示例。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-09
        • 2011-04-27
        • 2011-11-23
        • 2013-11-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多