How to fill form with JSON?

前端 未结 11 1562
灰色年华
灰色年华 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:38

    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.

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

提交回复
热议问题