【问题标题】:How to fill form with JSON?如何用 JSON 填写表格?
【发布时间】:2020-05-29 04:30:36
【问题描述】:

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

JSON:

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

要填写的表格

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

【问题讨论】:

    标签: javascript jquery json


    【解决方案1】:
    var json={ 
      "id" : 12,
      "name": "Jack",
      "description": "Description"
    };
    for(key in json)
    {
      if(json.hasOwnProperty(key))
        $('input[name='+key+']').val(json[key]);
    }
    

    srry 我以为是设置的 id 属性。

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

    【讨论】:

    • 使用该代码 sn-p,key 将泄漏到全局范围。它还需要一个hasOwnProperty 检查,以防止在扩展Object.prototype 时出现问题。
    • 谢谢。还要记住,表单元素可能不仅仅是&lt;input&gt;。它也可能有texarea, select, radio`。所以[name='+key+'] 可能比input[name='+key+']
    【解决方案2】:

    来到这里寻找不涉及 jQuery 或 DOM 扫描早午餐的解决方案,但没有找到...所以这是我的 vanilla 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)
    }
    <form>
      <input type="text" name="id"/>
      <input type="text" name="name"/>
      <input type="text" name="description"/>
    </form>

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • this[key] 应该做什么?您会在 name 属性中找到名称,而不是在具有相同名称和值的属性中(name 属性实际上包含值 name 的情况除外)。
      • @Guffa 你说得对;我一愣(因为前两个例子是nameid,它们也可以用作属性)。谢谢,我已经编辑了我的答案。
      【解决方案4】:

      jQuery Populate plugin 和@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"
      }
      

      form1(通过name属性匹配):

      <form>
          <input type="text" name="name" />
          <input type="text" name="id" />
          <textarea type="text" name="description" />
      </form>
      $('#form1').myPopulate(json, 'name');
      

      form2(通过alt属性匹配):

      <form id="form2">
          <input type="text" name="nick" alt="name" />
          <input type="text" name="identifier" alt="id" />
          <textarea type="text" name="desc" alt="description" />
      </form>
      $('#form2').myPopulate(json, 'alt');
      

      【讨论】:

      • 不需要var form = $(this);,只需要var form = this;,因为this此时已经引用了jQuery集合。
      【解决方案5】:

      在纯 JavaScript 中非常简单:

      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>

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

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

      【讨论】:

        【解决方案6】:

        您可能想看看jQuery Populate plugin

        虽然这是您唯一的用例,但您也可以手动完成。

        【解决方案7】:

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

        【讨论】:

        • 在这种情况下不需要 JSON 插件。
        【解决方案8】:

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

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

        【讨论】:

        • 链接已失效。
        【解决方案9】:

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

        var o = $.parseJSON(json);
        

        (注意:也可以在AJAX调用中指定数据类型'json',得到结果时已经解析为对象。)

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

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

        【讨论】:

        • o[e] 应该做什么?我想你的意思是e。 (这就是你在使用这样的混淆变量名时得到的结果。)此外,你应该在选择器中引用属性值,以防 in 包含特殊字符。此外,在整个文档中查找$('[name=foo]') 效率不高;最好使用上下文,或者先查找输入,然后过滤缓存的集合。有关示例,请参见 my answer
        【解决方案10】:

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

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

        【讨论】:

          【解决方案11】:

          我正在将此方法与 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>
          

          示例 json 数据:

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

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

          【讨论】:

            猜你喜欢
            • 2015-09-20
            • 1970-01-01
            • 1970-01-01
            • 2016-09-11
            • 2011-11-02
            • 2018-01-15
            • 2017-11-17
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多