ajax实现form表单提交

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/spt_dream/article/details/81316722

昨天在做 ajax 申请链接提交表单的时候,发现提交了两次,Debug 的时候,也能发现控制器会执行两次。当然,数据库里也是两条数据。然后今天起来,修改了一下,结果出现了中文乱码情况,原因是多次解码,这里大家可以百度 serialize 相关信息。

最终整理了一下代码,能够完美实现要求。不刷新提交表单,只提交一次,中文不乱吗。

代码如下

html 部分

  1. <form id="apply_link_form">
  2.  
  3.       <input type="text" name="link_name" id="link_name" placeholder="如:言曌博客" required="required">
  4.  
  5.        <input type="text" name="link_url" id="link_url" placeholder="如:https://liuyanzhao.com" required="required">
  6.  
  7.        <input type="text" name="link_description" id="link_description" placeholder="如:一个后端开发者的成长笔记" >
  8.  
  9.        <input type="text" name="link_owner_contact" id="link_owner_contact" placeholder="如:邮箱[email protected]" required="required">
  10.  
  11.        <input id="submit" name="submit" type="submit" value="提交申请" >
  12.         <
  13. </form>

注意:form 标签只填一个 id 即可,不用填 action 和 method

js 部分

  1. //ajax提交信息
  2.     $("#apply_link_form").submit(function(){
  3.         parent.layer.close(index); //再执行关闭
  4.         $.ajax({
  5.             async: false,
  6.             type: "POST",
  7.             url:'${pageContext.request.contextPath}/link/apply',
  8.             contentType : "application/x-www-form-urlencoded; charset=utf-8",
  9.             data:$("#apply_link_form").serialize(),
  10.             dataType: "text",
  11.             success: function () {
  12.  
  13.               },
  14.             error: function () {
  15.  
  16.             }
  17.         })
  18.     })

注意:第9行填 data:$("#formid").serialize() 最终数据是 name=tom&pass=123456 之类的

猜你喜欢

转载自blog.csdn.net/spt_dream/article/details/81316722