先准备一个servlet来接受ajax请求
package cn.zsp.servlet;
import cn.zsp.pojo.Person;
import com.google.gson.Gson;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AjaxServlet extends BaseServlet{
protected void javaScriptAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html; charset=UTF-8");
System.out.println("请求过来了");
Person person=new Person(1,"鹏哥");
// 需要先转成json格式的字符串
Gson gson =new Gson();
String s = gson.toJson(person);
resp.getWriter().write(s);
}
}
在html里的jsp模块里调用ajax请求
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
//在这里使用javaScript语言发起Ajax请求
function ajaxRequest() {
// 1、我们首先要创建XMLHttpRequest
var xmlHttpRequest=new XMLHttpRequest();
// 2、调用open方法设置请求参数
xmlHttpRequest.open("GET","http://localhost:8080/json_ajax/ajaxServlet?action=javaScriptAjax",true);
// 4、在send方法前绑定onreadystatechange事件,处理请求完成后的操作。
xmlHttpRequest.onreadystatechange=function () {
if (xmlHttpRequest.status==200 &&xmlHttpRequest.readyState==4)
{
var jsonObj=JSON.parse(xmlHttpRequest.responseText);
document.getElementById("div01").innerHTML= "编号是"+jsonObj.id+"名字是"+jsonObj.name;
}
}
// 3、调用send方法发送请求
xmlHttpRequest.send();
//
}
</script>
</head>
<body>
<button onclick="ajaxRequest()">ajax request</button>
<div id="div01">
</div>
</body>
</html>```