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

前端 未结 4 704
南笙
南笙 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);
    });
    
    0 讨论(0)
  • 2020-12-13 17:18

    You can get rid of all "if" statements by replacing your $.each with this:

    $.each(data, function(i, item){
      $("#"+item.field).val(item.value);
    });
    
    0 讨论(0)
  • 2020-12-13 17:20

    I noticed that element IDs are the same as fields in your JSON, how about:

    $(document).ready(function() {
        $('#svendor_name').bind("change", function()
        {
            var svendor = $("#svendor_name").val();
            svendor = svendor.replace(/&/g, '*');
            $.getJSON("get_vendors.php?sname=" + svendor,
            function(data) {
                    $.each(data, function(i, item) {
                        $('#' + item.field).val(item.value);
                    });
            });
        });
    });
    
    0 讨论(0)
  • 2020-12-13 17:23

    What is wrong with this?

    $.each(data,
        function(i, item) {
            $("#" + item.field).val(item.value);
        }
    });
    
    0 讨论(0)
提交回复
热议问题