如何使用JSON填写表单?

mar*_*osh 8 javascript jquery json

我得到ajax响应为JSON,需要用它填充表单.如何在jQuery或其他东西中做到这一点?有什么比使用更好的东西$(json).each()

JSON:

{ 
  "id" : 12,
  "name": "Jack",
  "description": "Description"
}
Run Code Online (Sandbox Code Playgroud)

填写表格

<form>
  <input type="text" name="id"/>
  <input type="text" name="name"/>
  <input type="text" name="description"/>
</form>
Run Code Online (Sandbox Code Playgroud)

End*_*ess 13

来这里寻找一个不涉及 jQuery 或 DOM 扫描早午餐的解决方案,但没有找到......所以这是我的普通 js 解决方案,为其他可能很久以前就放弃了 jQuery 的人带来了。

const data = { 
  "id" : 12,
  "name": "Jack",
  "description": "Description",
  "nonExisting": "works too"
}

const { elements } = document.querySelector('form')

for (const [ key, value ] of Object.entries(data) ) {
  const field = elements.namedItem(key)
  field && (field.value = value)
}
Run Code Online (Sandbox Code Playgroud)
<form>
  <input type="text" name="id"/>
  <input type="text" name="name"/>
  <input type="text" name="description"/>
</form>
Run Code Online (Sandbox Code Playgroud)


Baz*_*nga 8

var json={ 
  "id" : 12,
  "name": "Jack",
  "description": "Description"
};
for(key in json)
{
  if(json.hasOwnProperty(key))
    $('input[name='+key+']').val(json[key]);
}
Run Code Online (Sandbox Code Playgroud)

srry我认为这是设置的id属性.

这里:http://jsfiddle.net/anilkamath87/XspdN/


Mat*_*ens 5

假设data是JSON对象,您可以在$.getJSON回调中使用它:

var $inputs = $('form input');
$.each(data, function(key, value) {
  $inputs.filter(function() {
    return key == this.name;
  }).val(value);
});
Run Code Online (Sandbox Code Playgroud)


Ber*_*ron 0

您可能想看一下jQuery Populate 插件

尽管如果这是您唯一的用例,您也可以手动执行。

  • 旧链接 http://www.keyframesandcode.com/resources/javascript/jQuery/demos/populate-demo.html 不再有效。新链接是:http://davestewart.io/resources/javascript/jQuery/demos/populate-demo.html (2认同)