获取以上示例中的表单数据:
<form id="myForm"> <div class="form-group"> <label for="name" class="col-md-2 control-label">姓名:</label> <div class="col-md-8"> <input type="text" class="form-control" name="name" value="lily" /> </div> </div> <div class="form-group"> <label for="type" class="col-md-2 control-label">技能:</label> <div class="col-md-8"> <select class="form-control" name="skill"> <option value="1" selected>PHP</option> <option value="2">JAVA</option> </select> </div> </form>
方法1:
let json = $(‘#myForm’).serialize();
console.log(‘json : ‘,json); // 输出:name=lily&skill=1
方法2:
let data = {};
let value = $(‘#myForm’).serializeArray();
$.each(value, function (index, item) {
data[item.name] = item.value;
});
let json = JSON.stringify(data);
console.log(‘json : ‘,json);
// 输出:{“name”:”lily”,”skill”:”1″}