What is the best method to populate form with jQuery?
I have used jQuery Form plugin to submit the whole form data to server while Ajax. When the server code (php) returns, the retrieved data is in JSON format. What is the best method to populate the form with jQuery.
Here is what I want to do:
- The user enters the data on the form
- The user submits the form data (I use ajax to submit)
- The server code returns.
- The user has the ability to retrieve the entered data.
So for the step 4, I want to know what the best method to use to pop开发者_StackOverflowulate a form?
Thank you
If you can ensure that the returned JSON object contains property names that match your form fields, it can be quite simple to populate the form.
Of course, you need to first evaluate the retrieved JSON, either using eval
, or using a JSON library such as this for added security checks.
Then, you can just iterate over the object like this:
var obj = eval(json); /* or JSON.parse(json); */
for (var field in obj)
$('#' + field).val(obj[field]);
If your form contains non-textual fields (such as a select
) you could add an additional check to set the selected index instead.
精彩评论