How to fill form with JSON?

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

提交回复
热议问题