ajax实现form表单提交

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

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

代码如下

html 部分

  1. <form id="apply_link_form">
  2.       <input type="text" name="link_name" id="link_name" placeholder="如:言曌博客" required="required">
  3.        <input type="text" name="link_url" id="link_url" placeholder="如:https://liuyanzhao.com" required="required">
  4.        <input type="text" name="link_description" id="link_description" placeholder="如:一个后端开发者的成长笔记" >
  5.        <input type="text" name="link_owner_contact" id="link_owner_contact" placeholder="如:邮箱service@liuyanzhao.com" required="required">
  6.        <input id="submit" name="submit" type="submit" value="提交申请" >
  7.         <
  8. </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.             error: function () {
  14.             }
  15.         })
  16.     })

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

 

 

控制器代码

  1. @RequestMapping(value = "link/apply",method = {RequestMethod.POST})
  2. @ResponseBody
  3. public void applyLink(HttpServletRequest request) throws Exception {
  4.     String linkName = request.getParameter("link_name");;
  5.     String linkUrl = request.getParameter("link_url");
  6.     String linkDescription = request.getParameter("link_description");
  7.     String linkOwnerContact = request.getParameter("link_owner_contact");
  8.     LinkCustom linkCustom = new LinkCustom();
  9.     linkCustom.setLinkName(linkName);
  10.     linkCustom.setLinkUrl(linkUrl);
  11.     linkCustom.setLinkDescription(linkDescription);
  12.     linkCustom.setLinkOwnerContact(linkOwnerContact);
  13.     linkCustom.setLinkStatus((byte0);
  14.     linkCustom.setLinkCreateTime(new Date());
  15.     linkCustom.setLinkUpdateTime(new Date());
  16.     linkService.applyLink(linkCustom);
  17. }

 

效果图如下


 

查看数据表,已添加了一条数据


 

本文链接:https://liuyanzhao.com/6193.html

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半缘修道半缘君丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值