“Walk” JSON response and populate form fields — more efficient approach?

前端 未结 4 715
南笙
南笙 2020-12-13 16:36

I know there is a far more elegant/efficient way of doing this (in php I would use foreach) but with jQuery how can I walk the var/val pairs of a JSON response and populate

4条回答
  •  天涯浪人
    2020-12-13 17:11

    If your results looks like this:

    [{"field1":"value1","field2":"value2"}]
    

    Then the code provided by Seb and Chetan works

    $.each(data, function(i, item){
      $("#"+item.field).val(item.value);
    });
    

    If your results looks like this:

    {"field1":"value1","field2":"value2"}
    

    Then use this code

    $.each(data, function(field, value){
      $("#"+field).val(value);
    });
    

提交回复
热议问题