开发者

What is the best method to populate form with jQuery?

开发者 https://www.devze.com 2023-01-08 11:55 出处:网络
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 for

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:

  1. The user enters the data on the form
  2. The user submits the form data (I use ajax to submit)
  3. The server code returns.
  4. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消