How to fill form with JSON?

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

    jQuery Populate plugin and code proposed by @Mathias inspired me to make my own plugin:

    Here my myPopulate plugin code. It use attr parameter as name of elements attribute on to use for identifying them.

    (function($) {
        $.fn.myPopulate = function(json, attr) {
            var form = $(this);
            $.each(json, function(key, value) {
                form.children('[' + attr + '="' + key + '"]').val(value);
            });
        };
    })(jQuery);
    

    Using:

    { 
      "id" : 12,
      "name": "Jack",
      "description": "Description"
    }
    

    form1 (matching by name attribute):