Ajax的请求(post,get)
程序员文章站
2022-07-12 18:08:38
...
<%--
Created by IntelliJ IDEA.
User: linlin
Date: 2017/7/14
Time: 9:31
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function(){
$("[name=uname]").blur(function () {
var xhr=null;
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET","/FirstServlet?uname="+$("[name=uname]").val(),true);
xhr.onreadystatechange=function () {
if(xhr.readyState==4&&xhr.status==200){
var data=xhr.responseText;
var dom=document.getElementById("msg");
dom.innerText=data;
}
}
xhr.send(null);
})
})
</script>
<html>
<head>
<title>Title</title>
</head>
<body>
<input name="uname"><span id="msg"></span>
</body>
</html>
package cn.happy;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by linlin on 2017/7/14.
*/
public class FirstServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("uname");
if(name.equals("admin")){
response.getWriter().write("true2");
}else{
response.getWriter().write("false");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
对于请求我们分为Post 和Get 但是提交的的方法有一定区别,彼此的利害关系也不一样
上面是我们Get请求
下面是我们Post请求,没特大的变化。这也只是个入门。。。
<%--
Created by IntelliJ IDEA.
User: linlin
Date: 2017/7/14
Time: 9:31
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function(){
$("[name=uname]").blur(function () {
var xhr=null;
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("POST","/FirstServlet?uname="+$("[name=uname]").val(),true);
xhr.onreadystatechange=function () {
if(xhr.readyState==4&&xhr.status==200){
var data=xhr.responseText;
var dom=document.getElementById("msg");
dom.innerText=data;
}
}
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("uname="+$('[name=uname]').val());
})
})
</script>
<html>
<head>
<title>Title</title>
</head>
<body>
<input name="uname"><span id="msg"></span>
</body>
</html>