How to fill form with JSON?

前端 未结 11 1521
灰色年华
灰色年华 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: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;
      });
    });

    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

提交回复
热议问题