Home  >  Article  >  Web Front-end  >  Implementing mutual conversion of form elements to JSON by constructing AJAX parameters

Implementing mutual conversion of form elements to JSON by constructing AJAX parameters

亚连
亚连Original
2018-05-24 10:25:541303browse

This article mainly introduces the related introduction of JSON conversion of form elements by constructing AJAX parameters. Friends in need can refer to

ajax submission server data to sort out the conversion methods.

HTML:

1. Convert form elements to QueryString

var q = $('#fm,#UserId').serialize(); //q = UserName=UserName1&UserId=UserId1

2. Convert strings to JSON

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

You can use the jquery-json plug-in to achieve conversion and directly quote the example

var thing = {plugin: 'jquery-json', version: 2.3};
var encoded = $.toJSON( thing );
// '{"plugin":"jquery-json","version":2.3}'
var name = $.evalJSON( encoded ).plugin;
// "jquery-json"
var version = $.evalJSON(encoded).version;
// 2.3

3. Convert form elements to Name, Value array

var arr = $("#fm,#UserId").serializeArray();
/*[ 
{name: 'UserName', value: '"UserName"1'}, 
{name: 'UserId', value: 'UserId'}
] */

4. Convert form elements to JSON

$.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;
};
var obj = $('form').serializeObject();
/*obj: Object
UserId: "UserId1"
UserName: "UserName1"
__proto__: Object*/

5. JSON2FORM

$.getJSON('url_to_file', function(data) {
for (var i in data) {
$('input[name="'+i+'"]').val(data[i]);
}
}
data = {
"Name":"Emkay Entertainments",
"Address":"Nobel House, Regent Centre",
"Contact":"Phone"
} 
$('p#data').loadJSON(data);

Emkay Entertainments

Nobel House, Regent Centre Phone

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Ajax and cgi communication under Boa server (graphic tutorial)

Ajax Struts2 implements verification code verification function (Graphic tutorial)

Ajax click to continuously load the data list (Graphic tutorial)

The above is the detailed content of Implementing mutual conversion of form elements to JSON by constructing AJAX parameters. 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