简体   繁体   English

jQuery-在表单中填充数据的正确方法

[英]JQuery - Correct way to populate data in form

function getData(id) {
    $.getJSON('process.php?action=lookup&id='+id, parseInfo);       
    return false;
}

// Display data in form
function parseInfo(data) {  
  if (data.id > 0) {
    $('#txtaction').val('update');
    $('#txtbook_id').val(data.id);
  } else {
    $('#txtaction').val('');
    $('#txtbook_id').val('');
  }
}

Referring to the method above, is this the proper way to populate form fields? 参考上面的方法,这是填充表单字段的正确方法吗? Will it cause any problem when calling getData function if i have a long list of form fields to populate and attributes to change? 如果我要填充的表单字段和属性要更改的列表很长,那么在调用getData函数时会引起任何问题吗?

Thank you in advance for any comments! 预先感谢您的任何评论!

One tweak I'd make is to avoid repeating the selectors and val calls, too easy to add a field and forget to update one half of the if/else or the other: 我要进行的一项调整是避免重复选择器和val调用,太容易添加字段而忘记更新一半的if/else或另一半:

function parseInfo(data) {  
  var valid = data && data.id > 0;
  $('#txtaction').val(valid ? 'update' : '');
  $('#txtbook_id').val(valid ? data.id : '');
}

Side note: Doing this manually is fine for very small projects, but for anything of any size, you might look into any of the various MVC and MVVC tools or frameworks. 旁注:手动执行此操作非常适合小型项目,但是对于任何大小的项目,您都可以研究各种MVC和MVVC工具或框架。 There are many. 有许多。

This seems to be correct. 这似乎是正确的。 However keep in mind that JSON attribute names can't contain dashes so an alternate way to get around that problem would be: 但是请记住,JSON属性名称不能包含破折号,因此解决该问题的另一种方法是:

if (data['id'] > 0) {
    $('#txtaction').val('update');
    $('#txtbook_id').val(data['id']);
} else {
   $('#txtaction').val('');
   $('#txtbook_id').val('');
}

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

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