jQuery serializeArray()方法
描述
serializeArray()方法类似于.serialize()方法,用于序列化所有表单和表单元素,但返回一个JSON数据结构供您使用。
返回的JSON结构不是一个字符串。您必须使用插件或第三方库进行”字符串化”。
语法
以下是使用此方法的简单语法:
$.serializeArray( )
参数
以下是该方法所使用的所有参数的描述:
- NA
示例
假设我们在serialize.php文件中有以下PHP内容:
<?php
if( _REQUEST["name"] ) {name = _REQUEST['name'];
echo "Welcome ".name;
age =_REQUEST['age'];
echo "<br />Your age : ". age;sex = _REQUEST['sex'];
echo "<br />Your gender : ".sex;
}
?>
以下是一个简单的示例,显示了使用该方法的用法。
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
(document).ready(function() {("#driver").click(function(event){
.post( "/jquery/serialize.php",("#testform").serializeArray(),
function(data) {
('#stage1').html(data);
}
);
var fields =("#testform").serializeArray();
("#stage2").empty();
jQuery.each(fields, function(i, field){("#stage2").append(field.value + " ");
});
});
});
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id = "stage1" style = "background-color:blue;">
STAGE - 1
</div>
<br />
<div id = "stage2" style = "background-color:blue;">
STAGE - 2
</div>
<form id = "testform">
<table>
<tr>
<td><p>Name:</p></td>
<td><input type = "text" name = "name" size = "40" /></td>
</tr>
<tr>
<td><p>Age:</p></td>
<td><input type = "text" name = "age" size = "40" /></td>
</tr>
<tr>
<td><p>Sex:</p></td>
<td> <select name = "sex">
<option value = "Male" selected>Male</option>
<option value = "Female" selected>Female</option>
</select></td>
</tr>
<tr>
<td colspan = "2">
<input type = "button" id = "driver" value = "Load Data" />
</td>
</tr>
</table>
</form>
</body>
</html>