Javascript 如何用 JSON 填写表单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6937519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:51:12  来源:igfitidea点击:

How to fill form with JSON?

javascriptjqueryjson

提问by marioosh

I get ajax response as JSON and need to fill a form with it. How to do that in jQuery or something else ? Is something better than using $(json).each()?

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

JSON:

JSON:

{ 
  "id" : 12,
  "name": "Hyman",
  "description": "Description"
}

Form to fill

填写表格

<form>
  <input type="text" name="id"/>
  <input type="text" name="name"/>
  <input type="text" name="description"/>
</form>

采纳答案by Bertrand Marron

You might want to take a look at the jQuery Populate plugin.

您可能想看看jQuery Populate 插件

Although if this is the only use case you have, you might as well do it manually.

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

回答by Baz1nga

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

srry i thought it was the id property that was set.

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

here: http://jsfiddle.net/anilkamath87/XspdN/

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

回答by Mathias Bynens

Assuming datais the JSON object, you could use this inside the $.getJSONcallback:

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

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

回答by ryanpcmcquen

Pretty simple in pure JavaScript:

在纯 JavaScript 中非常简单:

https://jsfiddle.net/ryanpcmcquen/u8v47hy9/

https://jsfiddle.net/ryanpcmcquen/u8v47hy9/

var data = {
  foo: 1,
  bar: 2
};
var inputs = Array.prototype.slice.call(document.querySelectorAll('form input'));

Object.keys(data).map(function (dataItem) {
  inputs.map(function (inputItem) {
    return (inputItem.name === dataItem) ? (inputItem.value = data[dataItem]) : false;
  });
});
<form>
  <input name="foo">
  <input name="bar">
</form>

Edit: This also works with other inputs such as select, simply by replacing document.querySelectorAll('form input')with document.querySelectorAll('form input, form select').

编辑:这也适用于其他输入,例如select,只需替换document.querySelectorAll('form input')document.querySelectorAll('form input, form select')

This also gets around the global leak in this answer: https://stackoverflow.com/a/6937576/2662028

这也解决了这个答案中的全球泄漏:https: //stackoverflow.com/a/6937576/2662028

回答by Isaac Adams

I haven't seen a solution that accounts for a form with nested properties. Here it is.

我还没有看到解决具有嵌套属性的表单的解决方案。这里是。

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

回答by kodmanyagha

I'm using this method with iCheck elements. This method can work native check and radio inputs.

我将此方法与 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);
        }
    });
}

Example form:

示例形式:

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

Example json data:

示例 json 数据:

{
    "radio1": "3",
    "radio2": "1",
    "ssl": "0"
}

Edit: I tried populate plugin but it doesn't working with iCheck and other things for example select2, chosen, etc...

编辑:我尝试填充插件,但它不适用于 iCheck 和其他东西,例如 select2、selected 等...

回答by Endless

Came here searching for a solution that didn't involve jQuery or a brunch of DOM scaning, but didn't find one... so here is my vanilla js solution brought to you other guys that probably ditched jQuery long ago.

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

const data = { 
  "id" : 12,
  "name": "Hyman",
  "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)
}
<form>
  <input type="text" name="id"/>
  <input type="text" name="name"/>
  <input type="text" name="description"/>
</form>

回答by Alexander Beletsky

You might also consider usage of jQuery templates for that purpose:

您也可以考虑为此目的使用 jQuery 模板:

http://api.jquery.com/jQuery.template/

http://api.jquery.com/jQuery.template/

回答by Guffa

First you need to parse the JSON string so that you get an object that you can use:

首先,您需要解析 JSON 字符串,以便获得可以使用的对象:

var o = $.parseJSON(json);

(Note: You can also specify the data type 'json' in the AJAX call, then it will be parsed into an object already when you get the result.)

(注意:您也可以在 AJAX 调用中指定数据类型 'json',然后在您得到结果时它会被解析为一个对象。)

Then you can loop throught the properties in the object:

然后你可以遍历对象中的属性:

$.each(o, function(key, value){
  $('form [name=' + key + ']').val(value);
});

回答by mattkelly

Just use a JSON plugin for jQuery - such as jquery-json.

只需为 jQuery 使用 JSON 插件 - 例如jquery-json