How to fill form with JSON?

前端 未结 11 1520
灰色年华
灰色年华 2020-12-29 14:17

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() ?

<
相关标签:
11条回答
  • 2020-12-29 14:41

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

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

    0 讨论(0)
  • 2020-12-29 14:43

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

    0 讨论(0)
  • 2020-12-29 14:47

    Pretty simple in pure 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>

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

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

    0 讨论(0)
  • 2020-12-29 14:49
    var json={ 
      "id" : 12,
      "name": "Jack",
      "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.

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

    0 讨论(0)
  • 2020-12-29 14:55

    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);
              }
         });
    }
    
    0 讨论(0)
提交回复
热议问题