一、目的
使用Jquery獲取form中所有控件的值,並封裝成JSON
二、代碼實現
2.1 head
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<title>Document</title>
</head>
2.2 body
<body>
<form method="post" action="" id="form">
用戶名: <input type="text" name="username"><br>
密碼: <input type="text" name="pwd"><br>
<button type="submit" value="" id="submit_demo">提交</button>
</form>
</body>
2.3 script
<script>
function get_form_value(){
//保存控件名與控件值的字典
var d = {};
var t = $('#form').serializeArray();
$.each(t, function () {
d[this.name] = this.value;
})
return JSON.stringify(d)
}
$('#submit_demo').click(function () {
alert(get_form_value());
});
</script>
- serializeArray() 方法通過序列化表單值來創建對象(name 和 value)的數組
- .each() 對 jQuery 對象進行迭代,爲每個匹配元素執行函數。
2.4 運行結果
三、 全部代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<form method="post" action="" id="form">
用戶名: <input type="text" name="username"><br>
密碼: <input type="text" name="pwd"><br>
<button type="submit" value="" id="submit_demo">提交</button>
</form>
</body>
<script>
function get_form_value(){
var d = {};
var t = $('#form').serializeArray();
$.each(t, function () {
d[this.name] = this.value;
})
return JSON.stringify(d)
}
$('#submit_demo').click(function () {
alert(get_form_value());
});
</script>
</html>