Home  >  Article  >  Web Front-end  >  jQuery--Convert serialized values ​​​​to json method guidance

jQuery--Convert serialized values ​​​​to json method guidance

巴扎黑
巴扎黑Original
2017-08-05 16:46:431391browse

This article mainly introduces the relevant information about converting form values ​​serialized by Jquery into Json. It is very good and has reference value. Friends in need can refer to it

A child has a form and he wants to Get the form content in Json format. The children tried the following methods.

The serialized form value string can be obtained through $("#form").serialize().

For example:


a=1&b=2&c=3&d=4&e=5

Serialize the form value in the form of an array through $("#form").serializeArray()Output .


[ 
 {name: 'firstname', value: 'Hello'}, 
 {name: 'lastname', value: 'World'},
 {name: 'alias'}, // 值为空
]

None of them satisfy the children’s wish to get Json. After stack overflow, I found such a method


$.fn.serializeObject = function()
{
 var o = {};
 var a = this.serializeArray();
 $.each(a, function() {
 if (o[this.name] !== undefined) {
  if (!o[this.name].push) {
  o[this.name] = [o[this.name]];
  }
  o[this.name].push(this.value || '');
 } else {
  o[this.name] = this.value || '';
 }
 });
 return o;
};

Then you can get Json through $("#form").serializeObject(); Content.

The above is the detailed content of jQuery--Convert serialized values ​​​​to json method guidance. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn