<form id="title">
<input name='username'>用户名
<input name='password'>密码
</form>
<button id='submit' type="button">提交</button>
<button id='submit2' type="button">提交</button>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
//方法一
$("#submit").click(function(){
//serialize()函数将来自表单的数据转码了,所以需要解码才能显示正常数据
var title =decodeURIComponent($("#title").serialize());//获取form id=title的表单数据
console.log(title);
});
//方法二
$("#submit2").click(function(){
x=$("#title").serializeArray();
var arrayObj = new Array();
$.each(x, function(i, field){
console.log(field.name+':'+field.value);
});
});
</script>
实战例子:
<script>
//当id=submitadd的按钮被点击时
$("#submitadd").click(function(){
//serialize()函数将来自表单的数据转码了,所以需要解码才能显示正常数据
var title =decodeURIComponent($("#title").serialize());//获取form id=title的表单数据
//获取ckeditor的内容
var oEditor = CKEDITOR.instances.editor1;
var content = oEditor.getData();
//获取复选框内容,复选框name = check
var checkID=[];
$("input[name='check']:checked").each(function(i){
checkID[i] = $(this).val();
});
//判断内容是否填写
if(title=='title='){
html="<div class='alert alert-warning'><strong>题目没有填写</strong></div>";
$("#test").html(html);
}else if(content==''){
html="<div class='alert alert-warning'><strong>正文没有填写!</strong></div>";
$("#test").html(html);
}
$.ajax({
type:'post',
url:'http://127.0.0.1:5000/edit',
cache: false,
data:{
'title':title,
'text':content,
'checkID':checkID
}, //重点必须为一个变量如:data
contentType: "application/x-www-form-urlencoded; charset=utf-8",
success:function(data){
},
error:function(){
alert("请求失败")
}
})
})
</script>
- 在获取title表单时,如果表单为中文,就会出现%4E%此类utf-8的乱码,原因是因为serialize()将编码改变了,所以用decodeURIComponent将其解码
-
html="<div class='alert alert-warning'><strong>题目没有填写</strong></div>"; $("#test").html(html); //需要指定一个<div id='test'></div>才可以显示html
·