Home >Web Front-end >JS Tutorial >jQuery form serialization example code
This article mainly introduces the jQuery form serialization example code. Friends who need it can refer to it
No more nonsense, I will post the code directly for everyone. The specific code is as follows Said:
$(function(){ $('#send').click(function(){ $.ajax({ type: "GET", url: "test.json", data: {username:$("#username").val(), password:$("#password").val()}, // 参数为对象 dataType: "json", success: function(data){ // code... } }); }); }); $(function(){ $('#send').click(function(){ var username = $("#username").val(); var password = $("#password").val(); $.ajax({ type: "GET", url: "test.json", data: "username"+username+"&password"+password, // 参数为字符串拼接,并用&连接 dataType: "json", success: function(data){ // code... } }); }); });
The above is a regular ajax request code, which lists two transmission formats of data parameters.
In order to facilitate the acquisition of data parameters during ajax requests, jquery defines several quick methods.
1.serialize()
Usage: var data = $("form").serialize();
Return value: The form The content is serialized into a string.
In this way, when submitting form data with ajax, there is no need to list each parameter one by one. Just set the data parameter to $("form").serialize().
The core method is $.param(), which is used to serialize an array or object according to key/value,
var obj = {first:" one",last:"two"};
var str = $.param(obj);
console.log(str); // first=one&last=two
In addition, use serialize One advantage is that it comes with Chinese compilation and processing. Therefore, it is recommended to use serialize.
2.serializeArray()
Usage: var jsonData = $("form").serializeArray();
Return value: Serialize the page form into a JSON structure (key-value pair) object.
For example, [{"name":"lihui", "age":"20"},{...}] gets the data as jsonData[index].name
To sum up : When using ajax to submit form data, the data parameter can be set to $(form).serialize() or $(form).serializeArray(). In addition, it is recommended to refer to w3c for some details.
Finally add a complete example.
html:
<html> <head> <meta charset="utf-8"> </head> <body> <form id="demo"> <input type="text" value="demo1" name="demo1"> <input type="text" value="demo2" name="demo2"> <input type="text" value="demo3" name="demo3"> <input type="submit" value="提交" id="submit"> </form> </body> </html>
##
<script> // 别忘了引入jquery !!! $(function(){ $("#submit").click(function(){ // var data = $("form").serializeArray(); var data = $("form").serialize(); $.ajax({ type:"GET", url:"1.php", data:data, dataType:"json", success:function(data){ console.log(data); }, error:function(xhr,error){ console.log(error); } }) }) }) </script>php Reminder : Need to configure the php environment and open the server
<?php echo json_encode($_GET); ?>
The above is the detailed content of jQuery form serialization example code. For more information, please follow other related articles on the PHP Chinese website!