Best practice for populating a form?
I have a an ejs view that contains a form that I need to populate with data so that the underlying record can be edited. I've passed the object containing the data to the view and now see two ways to populate the form and would like some help deciding which one is better.
Option 1 - "server-side" population
I can put the form values directly into the elements like this:
<input type="text" id="txtFirstName" name="txtFirstName" value="<%= person.firstName%>" />
<input type="text" id="txtLastName" name="txtLastName" value="<%= person.lastName%>" />
...
etc
Option 2 - "client-side" population
Alternatively, I can return the entire object to the client and then use javascript to populate the form fields like this:
<script>
var data = "<%=JSON.stringify(person)%>".replace(/"/gi, '"');
var p = eval('(' + data + ')');
populateForm(p);
function populateForm (person) {
$("#txtFirstName").val( person.firstName );
$("#txtLastName").val( person.lastName );
....
etc
}
</script>
The benefit of Option 2 is that the function can easily be reused to repopulate the form if new data gets loaded via ajax. It also eliminates any need for escaping the data because its all in a js object already whereas Option 1 would require some type of html encoding and quotes escaping. Option 1, on the oth开发者_JAVA百科er hand works without js.
Is there a standard, best practice-y way to do this (and is it one of these options)?
I would load the data with ajax even in cases where it's not strictly necessary and render the template client side. That way your model is loaded into the javascript controller and pumped into your template view.
<script>
$(function (){
var person = null;
$.getJSON('/person',function (data) {
person = data;
var form = new EJS({url: '/form.ejs'}).render(person);
$('#formContainer').append(form);
});
});
</script>
精彩评论