最近在做一个Springboot项目,我在前端用表单提交并在js中取到表单,用ajax向后台提交json串之后出现了
type=Method Not Allowed, status=405). Request method ‘POST’ not suppo错误。
通过2小时不断查找终于发现了问题所在,还是自己基础知识太薄弱。下面是代码部分:
html中代码
<!--提示信息-->
<form class="form clearfix" method="post" id="loginForm" >
<div class="item item-fore1"><label for="loginname" class="login-label name-label"></label><input id="username" name="username" type="text" class="text" placeholder="请输入用户"/>
</div>
<div class="item item-fore2"><label for="nloginpwd" class="login-label pwd-label" ></label><input id="userpassword" name="userpassword" type="password" class="text" placeholder="用户密码" oncontextmenu="return false" onpaste="return false" />
</div>
<div class="Forgetpass"><a href="#">忘记密码?</a></div>
<button class="btn_login" type="submit" name="submit" id="userlogin">登 录</button>
</form>
js中代码
$(document).ready( // 在其中完成所有的jQuery代码
function(){
$("#userlogin").click(
function(){
alert("button click");
var usn = $("form input[name='username']").val();
var pwd = $("form input[name='userpassword']").val();
var jsonStr = JSON.stringify({username:usn,userpassword:pwd});
alert(jsonStr);
$.ajax({
url: "http://localhost:8080/userLogin",
type: "POST",
async : false, //同步请求
datatype: "JSON",
contentType :'application/json',
data: jsonStr,
success: function(data){
// alert(data.msg);
// alert(data.code);
location.href="index.html";
},
error: function(){
alert("提交失败");
window.location.refresh() ;
}
});
return false;
});
});
注意此处的return false 我出错的原因是因为没有加上return false,原因是ajax会帮我提交一次请求,但是在它提交之后,form又会再帮我提交一次,导致我ajax里面的location跳转就像没执行一样,所以在js中click事件要结束时添加代码return false;不让form提交请求即可。