我发现一个奇怪的问题:

jgongcheng 2015-02-04 04:05:23
点击button以后,表单先由ajax提交,然后无论后台返回什么结果,页面都会跳转到表单action属性指定的路劲,
也就是login.html
使用的是html、jquery、javascript,后台是spring mvc 代码如下:

html表单:

<form action="login.html" method="post" id="loginForm">
<input type="text" id="username" name="userName" />
<input type="password" id="password" name="password" />
<button class="btn btn-warning btn-loginsize" onClick="submitForm()">
登陆
</button>
<a href="#">忘记密码?</a>
<a href="#">注册</a>
</form>


jquery、javascript代码:

<script>
function submitForm() {
$.ajax({
cache: true,
type:"POST",
url: "verification.json",
dataType:"json",
data:$("#loginForm").serializeArray(),
async: false,
success:function(data){
if(data.flag == "1") { //登陆成功
alert("aa"); //这里返回正确
location.href="index.html";//这里没有作用,什么原因?
}else{ //登陆失败
alert("warnings");
}
},
error:function(data){
alert("error");
}
});
}
</script>



后台代码

@RequestMapping("/verification.json")
@ResponseBody
public Map<String, Object> verification(User user) {
Map<String, Object> map = new HashMap<String, Object>();

if (user.getUserName().equals("admin") && user.getPassword().equals("admin")) {
map.put("flag", "1");
} else {
map.put("flag", "0");
}
return map;
}
...全文
11078 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
jgongcheng 2015-02-04
  • 打赏
  • 举报
回复
引用 3 楼 slwsss 的回复:
<form action="login.html" method="post" id="loginForm" onsubmit="return false"> <button type="button" class="btn btn-warning btn-loginsize" onClick="submitForm()">
这样也可以 谢谢
u010007095 2015-02-04
  • 打赏
  • 举报
回复
引用 1 楼 slwsss 的回复:
button请始终为按钮规定 type 属性。Internet Explorer 的默认类型是 "button",而其他浏览器中(包括 W3C 规范)的默认值是 "submit"。
受教了 以前都不知道
u010007095 2015-02-04
  • 打赏
  • 举报
回复
<input type="button" class="btn btn-warning btn-loginsize" onClick="submitForm()"/>
jgongcheng 2015-02-04
  • 打赏
  • 举报
回复
好吧 根据楼上说的 我懂了 .. 在 submitForm()函数的最后加上 return false; 在HTML事件中 onClick="return submitForm()"
slwsss 2015-02-04
  • 打赏
  • 举报
回复
<form action="login.html" method="post" id="loginForm" onsubmit="return false"> <button type="button" class="btn btn-warning btn-loginsize" onClick="submitForm()">
jgongcheng 2015-02-04
  • 打赏
  • 举报
回复
引用 1 楼 slwsss 的回复:
button请始终为按钮规定 type 属性。Internet Explorer 的默认类型是 "button",而其他浏览器中(包括 W3C 规范)的默认值是 "submit"。
那么怎样才能让button不提交表单 而是交给ajax提交和跳转呢?
slwsss 2015-02-04
  • 打赏
  • 举报
回复
button请始终为按钮规定 type 属性。Internet Explorer 的默认类型是 "button",而其他浏览器中(包括 W3C 规范)的默认值是 "submit"。

87,992

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧