Heim  >  Artikel  >  Web-Frontend  >  jQuery中验证表单提交方式及序列化表单内容的实现_jquery

jQuery中验证表单提交方式及序列化表单内容的实现_jquery

WBOY
WBOYOriginal
2016-05-16 17:05:15967Durchsuche

之前项目中使用的表单提交方式

使用form()方法可以将提交事件脱离submit按钮,绑定到任何事件中

复制代码 代码如下:

function addSubmit(){
$('#addForm').form('submit', {
url : _basePath + '/@Controller/@RequestMapping',
onSubmit : function() {
if(boolean){//放置能否提交的判断条件
$.messager.show({
title:'提示',msg:'不符合保存条件',
showType:'fade',style:{right:'',bottom:''}
});
return false;//阻止表单提交
}
return $('#addForm').form('validate');//判断required项是否全部有值
},
success : function(data) {
var obj = jQuery.parseJSON(data);//将返回的JSON转化为所需对象(ResponseData)
if (!obj.success) {//判断返回的ResponseData对象中标示状态的属性值
$.messager.show({
title:'提示',msg:'保存失败',
showType:'fade',style:{right:'',bottom:''}
});
} else {
$.messager.show({
title:'提示',msg:'保存成功',
showType:'fade',style:{right:'',bottom:''}
});
$("#addWin").window("close");//关闭提交pwkk
query();//刷新结果集
}
}
});
}

今天在《锋利的jQuery》中又读到这样一种提交方式,使用ajax封装了表单内容用post提交
复制代码 代码如下:

$("#btn").click(function() {
$.get("get.php", {username:$("#username").val(), password:$("#password").val()}, function(data, textStatus) {//将表单中的数据逐条取出后封装上传
$("#target").html(data);//将返回值填充至页面中
});
});

而后有一个简化版,使用serialize()方法序列化
复制代码 代码如下:

$("#btn").click(function() {
$.get("get.php", $("#form").serialize(), function(data, textStatus) {//将表单中的数据逐条取出后封装上传
$("#target").html(data);//将返回值填充至页面中
});
});

serialize()方法可以自动编码,而且除表单之外的如checkbox等对象也可以使用其进行转换

同时还有serializeArray()方法可以将元素序列化后返回数组形式的JSON对象,而非JSON字符串

即无需使用jQuery.parseJSON()方法进行转换

返回值可直接使用类似$.each()等方法进行操作使用
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn