ajaxPOST请求
post请求有一个请求头
Content-Type
默认是
Content-Type: application/x-www-form-urlencoded
我们之前在表单里面进行请求的时候
会有默认的这个Content-Type
但是现在我们用ajax请求
就需要我们自己去写这个Content-Type
我们来捋一下
open方法: xmlHttp.open("POST".....
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
send:
xmlHttp.send("username=abc&password=123");
发送请求的时候,指定请求体
如果请求的时候带有参数,一般都用post
我们来写Servlet
public class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("hello world");
resp.getWriter().print("hello world");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username + "," + password);
System.out.println("hello world POST POST");
resp.getWriter().print("hello world POST POST");
}
}
然后是jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>测试</title>
<script type="text/javascript">
//在文档加载完成后就会执行
window.onload = function () {
//得到btn元素
var btn = document.getElementById("btn");
//给btn的click事件注册监听
//在btn被点击的时候执行
btn.onclick = function () {
//创建xmlHttpRequest对象
var xmlHttp = createXMLHttpRequest()
//打开与服务器的连接
//指定 1.方法 2.url 3.是否异步
xmlHttp.open("POST", "<c:url value='/test' />", true);
//设置请求头
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//发送请求,get方法,给出null请求体
xmlHttp.send("username=abc&password=123");
//给异步对象的onreadystatechange事件注册监听
xmlHttp.onreadystatechange = function () {
//当xmlHttp的状态发生变化的时候,就会执行
//判断readyState为4状态,服务器响应状态码status为200
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
//获取responseText文本格式的响应内容
var responseText = xmlHttp.responseText;
//获取h1元素对应的DOM对象
var h1 = document.getElementById("h1");
h1.innerHTML = responseText;
}
};
}
}
function createXMLHttpRequest() {
return new XMLHttpRequest()
}
</script>
</head>
<body>
<button id="btn">button</button>
<h1 id="h1"></h1>
</body>
</html>