现在的位置: 首页 > 搜索技术 > 正文

ajax如何提交form表单数据

2020年01月06日 搜索技术 ⁄ 共 1603字 ⁄ 字号 评论关闭

  对于form表单数据的提交,我们一般都会想到使用ajax提交,那么,ajax如何来提交form表单数据呢?接下来的这篇文章就来给大家来介绍关于ajax提交form表单数据方法,有需要的伙伴可以参考一下。


  ajax如何提交form表单数据


  ajax提交form表单数据可以分为两种,一种是无返回结果的,就是将表单数据提交给后台,后台处理完就完了;另一种就是有返回结果的,后台执行成功或失败的信息需要返回到前台。


  ajax本身属于有返回结果的一类,其中的success方法就是处理后台返回结果的。


  ajax提交form表单数据有返回结果的实现方式:将form表单数据序列化

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>login test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="ajax方式">
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
function login() {
$.ajax({ //几个参数需要注意一下
type: "POST",//方法类型
dataType: "json",//预期服务器返回的数据类型
url: "/users/login" ,//url
data: $('#form1').serialize(),
success: function (result) {
console.log(result);//打印服务端返回的数据(调试用)
if (result.resultCode == 200) {
alert("SUCCESS");
}
;
},
error : function() {
alert("异常!");
}
});
} </script></head><body><div id="form-div">
<form id="form1" onsubmit="return false" action="##" method="post">
<p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" size="15" value=""/></p>
<p>密 码:<input name="password" type="password" id="TextBox2" tabindex="2" size="16" value=""/></p>
<p><input type="button" value="登录" onclick="login()">&nbsp;<input type="reset" value="重置"></p>
</form></div></body></html>

  注意:这种方式提交form表单数据需要注意的是form表单中的项一定要有name属性,后台获取的键值对为key=name值,value=各项值,注意无论是input标签还是span或者是其他标签,一定要有name属性,没有name属性后台是获取不到该项的。

抱歉!评论已关闭.