将嵌套的json对象值绑定到表单字段

将嵌套的json对象值绑定到表单字段

问题描述:

我正在构建一个动态表单来编辑json对象中的数据。首先,如果存在这样的事情让我知道。我宁愿不建立它,但我已经搜索了很多次的工具,并找到只需要输入引号的树状结构。我会很乐意将所有的值视为字符串。这种编辑功能适用于最终用户,因此它需要简单且不会令人生畏。将嵌套的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)); 
} 
+2

所以你想要生成基于对象的表单并将表单字段绑定到对象属性?对象结构是怎样的? JSON只是一个字符串表示形式,您会发现只需处理Javascript对象并在需要时序列化为JSON即可。 – Anurag 2010-05-13 21:42:39

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

该解决方案已抵达。 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/

有直接加载JSON数据转换成另一种形式简单的模板引擎。请参阅http://plugins.jquery.com/project/loadJSON插件。它的工作方式与杰克放在这里的方式类似,但它使用纯HTML作为模板。

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