js實現post方式的異步請求

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>ajax</title>
<script src="/ajax/js/jquery-3.3.1.min.js"></script>
</head>
<body>
<form action="http://www.ubfgho.com/" method="post" enctype="application/x-www-form-urlencoded">
姓名:<input type="text" name="name"><span></span><br>
密碼:<input type="password" name="psw"><br>
<input type="submit" value="提交"><br>
</form>
</body>
<script>
//js實現post方式的異步請求
$(':text').blur(function () {
var name1=$(this).val().trim()
//1、建立發送異步請求的對象req
var req=XMLHttpRequest();
//2、準備發送
req.open("POST","ajax/login",true)
//3、設置請求頭
req.setRequestHeader("Content-type","application/x-www-form-urlencoded")
//4、發送
req.send("name"+name1)

//回調參數
req.onreadystatechange=function () {
if (req.readyState==4&&req.status==200){
$("span").html(req.responseText).css("color","red")
}
}
})




//1、失去焦點事件--判斷姓名是否爲空
$(':text').blur(function () {
var v=$(this).val()
if (v.trim()==""){
$("span").html("姓名爲空").css("color","red")
}else{
$("span").html("")//清空span
}
})
//2、提交事件---點擊提交按鈕觸發submit
$("form").submit(function () {
//選中text文本
var v=$(':text').val().trim();
if (v==""){
//若是姓名爲空。就返回false,阻止提交,
return false
}
})


</script>
</html>

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String name=request.getParameter("name");
boolean b=dao.selectName(name);
String msg=b?"用戶名已被佔用":"用戶名正常";
response.setContentType("text/html;charset=UTF-8"); response.getWriter().write(msg);}
相關文章
相關標籤/搜索