Javascript 如何用JSON填充表单?
我得到的ajax响应是JSON,需要用它填充表单。如何在jQuery或其他东西中做到这一点?是否比使用Javascript 如何用JSON填充表单?,javascript,jquery,json,Javascript,Jquery,Json,我得到的ajax响应是JSON,需要用它填充表单。如何在jQuery或其他东西中做到这一点?是否比使用$(json).each()更好 JSON: 填写表格 <form> <input type="text" name="id"/> <input type="text" name="name"/> <input type="text" name="description"/> </form> 只需为jQuery使用一个J
$(json).each()
更好
JSON:
填写表格
<form>
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="text" name="description"/>
</form>
只需为jQuery使用一个JSON插件即可-例如。您可能想看看
尽管如果这是您仅有的用例,您也可以手动执行
var json={
"id" : 12,
"name": "Jack",
"description": "Description"
};
for(key in json)
{
if(json.hasOwnProperty(key))
$('input[name='+key+']').val(json[key]);
}
Sry我以为设置的是id属性
这里:您也可以考虑使用jQuery模板:
首先,您需要解析JSON字符串,以便获得可以使用的对象:
var o = $.parseJSON(json);
(注意:您还可以在AJAX调用中指定数据类型“json”,然后在得到结果时,它将被解析为一个对象。)
然后可以循环浏览对象中的属性:
$.each(o, function(key, value){
$('form [name=' + key + ']').val(value);
});
假设
data
是JSON对象,您可以在$回调中使用它
var $inputs = $('form input');
$.each(data, function(key, value) {
$inputs.filter(function() {
return key == this.name;
}).val(value);
});
@Mathias提出的代码启发我制作自己的插件:
这里是我的myPopulate插件代码。它使用attr
参数作为属性上的元素名称,用于标识它们
(function($) {
$.fn.myPopulate = function(json, attr) {
var form = $(this);
$.each(json, function(key, value) {
form.children('[' + attr + '="' + key + '"]').val(value);
});
};
})(jQuery);
使用:
{
"id" : 12,
"name": "Jack",
"description": "Description"
}
表格1(按名称
属性匹配):
在纯JavaScript中非常简单:
var数据={
傅:1,,
酒吧:2间
};
var inputs=Array.prototype.slice.call(document.querySelectorAll('forminput');
Object.keys(数据).map(函数(数据项){
inputs.map(函数(inputItem){
返回(inputItem.name==dataItem)?(inputItem.value=data[dataItem]):false;
});
});代码>
我还没有看到一个解决方案可以解释具有嵌套属性的表单。
给你
//pass in the parent object name, if there is one
let parentName = 'optional';
SyncJsonToForm(data, parentName);
function SyncJsonToForm(obj, path = '') {
let subpath = path === '' ? path : path + '.';
$.each(obj, function (key, value) {
let jsonPath = subpath + key;
// to debug a particular field (or multiple fields), replace the following JsonPath(s) with the desired property(ies)
if ([''].includes(jsonPath)) {
console.log(jsonPath);
debugger;
}
// update the value for the jsonPath
$(`[name="${jsonPath}"]`).val(value);
if (typeof value === "object") {
SyncJsonToForm(value, jsonPath);
}
});
}
我将此方法用于iCheck元素。此方法可用于本地检查和无线电输入
populateForm(frm, data) {
console.log(data);
$.each(data, function(key, value) {
var ctrl = $("[name=" + key + "]", frm);
switch (ctrl.prop("type")) {
case "radio":
if (
ctrl.parent().hasClass("icheck-primary") ||
ctrl.parent().hasClass("icheck-danger") ||
ctrl.parent().hasClass("icheck-success")
) {
// raido kutularında aynı isimden birden fazla denetçi olduğu için bunları döngüyle almak lazım
// multiple radio boxes has same name and has different id. for this we must look to each html element
$.each(ctrl, function(ctrlKey, radioElem) {
radioElem = $(radioElem);
console.log(radioElem);
console.log(radioElem.attr("value"));
if (radioElem.attr("value") == value) {
radioElem.iCheck("check");
} else {
radioElem.iCheck("uncheck");
}
});
} else {
$.each(ctrl, function(ctrlKey, radioElem) {
radioElem = $(radioElem);
console.log(radioElem);
console.log(radioElem.attr("value"));
if (radioElem.attr("value") == value) {
radioElem.attr("checked", value);
} else {
radioElem.attr("checked", value);
}
});
}
break;
case "checkbox":
if (
ctrl.parent().hasClass("icheck-primary") ||
ctrl.parent().hasClass("icheck-danger") ||
ctrl.parent().hasClass("icheck-success")
) {
if (ctrl.attr("value") == value) {
ctrl.iCheck("check");
} else {
ctrl.iCheck("uncheck");
}
} else {
ctrl.removeAttr("checked");
ctrl.each(function() {
if (value === null) value = "";
if ($(this).attr("value") == value) {
$(this).attr("checked", value);
}
});
}
break;
default:
ctrl.val(value);
}
});
}
示例表格:
<form id="form1">
<div className="form-group row">
<label className="col-sm-3 col-form-label">
{window.app.translate(
"iCheck Radio Example 1"
)}
</label>
<div className="col-sm-9">
<div className="icheck-primary">
<input
type="radio"
id="radio1_0"
name="radio1"
value="0"
/>
<label for="radio1_0">
{window.app.translate(
"Radio 1 0"
)}
</label>
</div>
<div className="icheck-primary">
<input
type="radio"
id="radio1_1"
name="radio1"
value="1"
/>
<label for="radio1_1">
{window.app.translate(
"Radio 1 1"
)}
</label>
</div>
<div className="icheck-primary">
<input
type="radio"
id="radio1_2"
name="radio1"
value="2"
/>
<label for="radio1_2">
{window.app.translate(
"Radio 1 2"
)}
</label>
</div>
</div>
</div>
<div className="form-group row">
<label className="col-sm-3 col-form-label">
{window.app.translate(
"iCheck Radio Example 2"
)}
</label>
<div className="col-sm-9">
<div className="icheck-primary">
<input
type="radio"
id="radio2_0"
name="radio2"
value="0"
/>
<label for="radio2_0">
{window.app.translate(
"Radio 2 0"
)}
</label>
</div>
<div className="icheck-primary">
<input
type="radio"
id="radio2_1"
name="radio2"
value="1"
/>
<label for="radio2_1">
{window.app.translate(
"Radio 2 1"
)}
</label>
</div>
<div className="icheck-primary">
<input
type="radio"
id="radio2_2"
name="radio2"
value="2"
/>
<label for="radio2_2">
{window.app.translate(
"Radio 2 2"
)}
</label>
</div>
</div>
</div>
<div className="form-group row">
<label
htmlFor="ssl"
className="col-sm-3 col-form-label"
>
{window.app.translate("SSL")}
</label>
<div className="col-sm-9">
<div className="form-group row">
<div className="col-sm-12">
<div className="icheck-primary d-inline">
<input
type="checkbox"
id="ssl"
name="ssl"
value="1"
/>
<label for="ssl" />
</div>
</div>
</div>
</div>
</div>
</form>
编辑:我尝试填充插件,但它无法与iCheck和其他东西(例如select2、Selected等)一起使用。来这里搜索一个解决方案,该解决方案不涉及jQuery或DOM扫描,但没有找到。。。这是我给大家带来的香草js解决方案,其他人可能早就抛弃了jQuery
const data={
“id”:12,
“姓名”:“杰克”,
“说明”:“说明”,
“不存在”:“也有效”
}
const{elements}=document.querySelector('form')
for(对象项(数据)的常量[键,值]){
常量字段=elements.namedItem(键)
字段&(field.value=value)
}
o[e]
应该做什么?我想你的意思是e
。(这就是使用模糊变量名时得到的结果。)此外,还应在选择器中引用属性值,以防中包含特殊字符。另外,在整个文档中查找$('[name=foo]')
也不是很有效;最好使用上下文,或者先查找输入,然后过滤缓存的集合。例如,请参阅。本例中不需要JSON插件。使用该代码段,key
将泄漏到全局范围。它还需要一个hasOwnProperty
检查,以防止Object.prototype
扩展时出现问题。谢谢。还要记住,表单元素可能不仅仅是
。它还可能有texarea
,选择,
radio`。所以[name='+key+']
可能比input[name='+key+']
宽这个[key]
应该做什么?您可以在name
属性中找到名称,而不是在具有相同名称和值的属性中(除非name
属性实际包含值name
)。@Guffa您完全正确;我一时糊涂了(因为前两个示例是name
和id
,这两个示例也可以用作属性)。谢谢,我已经编辑了我的答案。不需要var form=$(这个)代码>,只需执行var form=this
因为此
已经引用了此时的jQuery集合。链接已失效。旧链接不再处于活动状态。新链接是:
//pass in the parent object name, if there is one
let parentName = 'optional';
SyncJsonToForm(data, parentName);
function SyncJsonToForm(obj, path = '') {
let subpath = path === '' ? path : path + '.';
$.each(obj, function (key, value) {
let jsonPath = subpath + key;
// to debug a particular field (or multiple fields), replace the following JsonPath(s) with the desired property(ies)
if ([''].includes(jsonPath)) {
console.log(jsonPath);
debugger;
}
// update the value for the jsonPath
$(`[name="${jsonPath}"]`).val(value);
if (typeof value === "object") {
SyncJsonToForm(value, jsonPath);
}
});
}
populateForm(frm, data) {
console.log(data);
$.each(data, function(key, value) {
var ctrl = $("[name=" + key + "]", frm);
switch (ctrl.prop("type")) {
case "radio":
if (
ctrl.parent().hasClass("icheck-primary") ||
ctrl.parent().hasClass("icheck-danger") ||
ctrl.parent().hasClass("icheck-success")
) {
// raido kutularında aynı isimden birden fazla denetçi olduğu için bunları döngüyle almak lazım
// multiple radio boxes has same name and has different id. for this we must look to each html element
$.each(ctrl, function(ctrlKey, radioElem) {
radioElem = $(radioElem);
console.log(radioElem);
console.log(radioElem.attr("value"));
if (radioElem.attr("value") == value) {
radioElem.iCheck("check");
} else {
radioElem.iCheck("uncheck");
}
});
} else {
$.each(ctrl, function(ctrlKey, radioElem) {
radioElem = $(radioElem);
console.log(radioElem);
console.log(radioElem.attr("value"));
if (radioElem.attr("value") == value) {
radioElem.attr("checked", value);
} else {
radioElem.attr("checked", value);
}
});
}
break;
case "checkbox":
if (
ctrl.parent().hasClass("icheck-primary") ||
ctrl.parent().hasClass("icheck-danger") ||
ctrl.parent().hasClass("icheck-success")
) {
if (ctrl.attr("value") == value) {
ctrl.iCheck("check");
} else {
ctrl.iCheck("uncheck");
}
} else {
ctrl.removeAttr("checked");
ctrl.each(function() {
if (value === null) value = "";
if ($(this).attr("value") == value) {
$(this).attr("checked", value);
}
});
}
break;
default:
ctrl.val(value);
}
});
}
<form id="form1">
<div className="form-group row">
<label className="col-sm-3 col-form-label">
{window.app.translate(
"iCheck Radio Example 1"
)}
</label>
<div className="col-sm-9">
<div className="icheck-primary">
<input
type="radio"
id="radio1_0"
name="radio1"
value="0"
/>
<label for="radio1_0">
{window.app.translate(
"Radio 1 0"
)}
</label>
</div>
<div className="icheck-primary">
<input
type="radio"
id="radio1_1"
name="radio1"
value="1"
/>
<label for="radio1_1">
{window.app.translate(
"Radio 1 1"
)}
</label>
</div>
<div className="icheck-primary">
<input
type="radio"
id="radio1_2"
name="radio1"
value="2"
/>
<label for="radio1_2">
{window.app.translate(
"Radio 1 2"
)}
</label>
</div>
</div>
</div>
<div className="form-group row">
<label className="col-sm-3 col-form-label">
{window.app.translate(
"iCheck Radio Example 2"
)}
</label>
<div className="col-sm-9">
<div className="icheck-primary">
<input
type="radio"
id="radio2_0"
name="radio2"
value="0"
/>
<label for="radio2_0">
{window.app.translate(
"Radio 2 0"
)}
</label>
</div>
<div className="icheck-primary">
<input
type="radio"
id="radio2_1"
name="radio2"
value="1"
/>
<label for="radio2_1">
{window.app.translate(
"Radio 2 1"
)}
</label>
</div>
<div className="icheck-primary">
<input
type="radio"
id="radio2_2"
name="radio2"
value="2"
/>
<label for="radio2_2">
{window.app.translate(
"Radio 2 2"
)}
</label>
</div>
</div>
</div>
<div className="form-group row">
<label
htmlFor="ssl"
className="col-sm-3 col-form-label"
>
{window.app.translate("SSL")}
</label>
<div className="col-sm-9">
<div className="form-group row">
<div className="col-sm-12">
<div className="icheck-primary d-inline">
<input
type="checkbox"
id="ssl"
name="ssl"
value="1"
/>
<label for="ssl" />
</div>
</div>
</div>
</div>
</div>
</form>
{
"radio1": "3",
"radio2": "1",
"ssl": "0"
}