步骤:
1.创建核心对象
var xmlhttp;
2. 建立连接
参数:
1. 请求方式:GET、POST
* get方式,请求参数在URL后边拼接。send方法为空参
* post方式,请求参数在send方法中定义
2. 请求的URL:
3. 同步或异步请求:true(异步)或 false(同步)
xmlhttp.open(“GET”,“ajaxS?key=ajax&val=lala”);
3.发送请求
xmlhttp.send();
4.接受并处理来自服务器的响应结果
获取方式 :xmlhttp.responseText,即当服务器响应成功后再获取
当xmlhttp对象的就绪状态改变时,触发事件onreadystatechange。
判断readyState就绪状态是否为4,判断status响应状态码是否为200,最后获取服务器的响应结果
代码为
package cn.yunhe.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/ajaxS")
public class AjaxS extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String key = req.getParameter("key");
String val = req.getParameter("val");
System.out.println(key+"---"+val);
PrintWriter out = resp.getWriter();
out.write("hello world");
out.close();
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<button>ajax</button>
<script>
let btn = document.getElementsByTagName("button")[0];
btn.onclick = function () {
//1.创建核心对象
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//2. 建立连接
xmlhttp.open("GET","ajaxS?key=ajax&val=lala");
//3.发送请求
xmlhttp.send();
//4.接受并处理来自服务器的响应结果
xmlhttp.onreadystatechange=function()
{
//判断readyState就绪状态是否为4,判断status响应状态码是否为200
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//获取服务器的响应结果
let responseText = xmlhttp.responseText;
alert(responseText);
}
}
}
</script>
</body>
</html>
运行结果截图: