jQuery how to load some json records into a form fields?

时间秒杀一切 提交于 2019-11-28 07:05:12
William W. Doyle

Or if your data return was fieldname value pairs like:

{"firstname" : "John", "lastname" : "Doe"}

you could do it like:

$.getJSON('url_to_file', function(data) {
    for (var i in data) {
        $('input[name="'+i+'"]').val(data[i]);
    }
});

Could you take a look at the JQuery loadJSON plugin on the http://code.google.com/p/jquery-load-json/ ? On the page http://code.google.com/p/jquery-load-json/wiki/WorkingWithFormElements is explained how this plugin load JSON object into the form. You can also find one live example here http://jquery-load-json.googlecode.com/svn/trunk/edit.html?ID=17. I think that this is exactly what you need. Just create empty form and load json in the form using the following code:

$('form').loadJSON(data);

This plugin handles all form elements such as check boxes, select list radio buttons etc. If you use it you will need to download plugin from the http://code.google.com/p/jquery-load-json/source/browse/trunk/scripts/jquery.loadJSON.js.

So, what's wrong with $.getJSON? It works fine:

$.getJSON("1.json", function(data) {
  $('input[name="firstname"]').val(data["data"]);
  $('input[name="lastname"]').val(data["size"]);
});

You may also use $.get like below;

$.get('your_file.[php/json]',function(d){
    $("input[name='firstname']").val(d.data);
    $("input[name='firstname']").val(d.size);
},'json');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!