简体   繁体   English

使用jquery使用JSON数据重新填充表单

[英]Use jquery to re-populate form with JSON data

I have an HTML form, that I save to the database via ajax. 我有一个HTML表单,我通过ajax保存到数据库。 To get the query string of key/value pairs, I have used the very convenient serialize function, like this: 要获取键/值对的查询字符串,我使用了非常方便的serialize函数,如下所示:

var myData = $("form#form_id").serialize();
$.ajax({
    url: "my_save_script.php",
    type: "post",
    data: myData,
    success: function(msg){
        alert(msg);
    }
});

Now I want to load a blank form, and re-populate it with the data from the database, which is delivered from an ajax call as a JSON string. 现在我想加载一个空白表单,并使用数据库中的数据重新填充它,该数据从ajax调用作为JSON字符串传递。 I have been able to get a Javascript object with the correct key/value pairs like this: 我已经能够获得具有正确键/值对的Javascript对象,如下所示:

data = $.parseJSON(data);
data = data[0];

What is the simplest, most elegant way to re-populate the form? 重新填充表单最简单,最优雅的方法是什么?

keep in mind the input elements of the form are text, select, checkbox, and radio. 请记住,表单的输入元素是文本,选择,复选框和广播。 The names of the input elements are the same as the names of the database columns, and are the keys of the key/value pairs in the above data object. 输入元素的名称与数据库列的名称相同,并且是上述data对象中键/值对的键。 This is why the serialize function works so well for me 这就是为什么serialize功能对我来说非常好

I'd say the easiest way would be something along these lines: 我想说最简单的方法就是这样:

// reset form values from json object
$.each(data, function(name, val){
    var $el = $('[name="'+name+'"]'),
        type = $el.attr('type');

    switch(type){
        case 'checkbox':
            $el.attr('checked', 'checked');
            break;
        case 'radio':
            $el.filter('[value="'+val+'"]').attr('checked', 'checked');
            break;
        default:
            $el.val(val);
    }
});

Basically, the only ones that are odd are the checkboxes and radios because they need to have their checked property, well, checked . 基本上,只有那些有奇怪的复选框和收音机,因为他们需要有自己的checked属性,好了, 检查 The radios are a little more complex than the checkboxes because not only do we need to check them, we need to find the right ONE to check (using the value). 无线电比复选框稍微复杂一些,因为我们不仅要检查它们,还需要找到合适的ONE进行检查(使用该值)。 Everything else (inputs, textareas, selectboxes, etc.) should just have its value set to the one that's returned in the JSON object. 其他所有内容(输入,textareas,选择框等)应该将其值设置为JSON对象中返回的值。

jsfiddle: http://jsfiddle.net/2xdkt/ jsfiddle: http//jsfiddle.net/2xdkt/

If data[0] contains the name of the field and data[1] contains the value then you can do the following: 如果data [0]包含字段的名称,而data [1]包含该值,则可以执行以下操作:

You can do something like this for text boxes: 您可以为文本框执行以下操作:

$("[name="+data[0]+"]").val(data[1]);

Then something like this for selects: 然后选择这样的东西:

$("[name="+data[0]+"]").val(data[1]);

Please note that check boxes and radio buttons are only serialized if they are checked. 请注意,复选框和单选按钮仅在选中后才会序列化。

So something like this for check boxes (before jQuery 1.6+): 所以这样的复选框(在jQuery 1.6+之前):

$("[name="+data[0]+"]").attr('checked','checked');

The radio button might need some additional work depending on how you're differentiating between the different ones. 单选按钮可能需要一些额外的工作,具体取决于您如何区分不同的工作。 (IE Id, value, etc..) (IE Id,值等..)

I suggest you change the way you are making an ajax request. 我建议你改变你发出ajax请求的方式。 Use .post() 使用.post()

$.post("my_save_script.php", {
         data: myData,
    }, function(data) {
        $.each(data, function(i, item){
            $("#"+item.field).val(item.value);
        });      
    }, 
"json");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM