js代码

<!DOCTYPE html PUBLIC "‐//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http‐equiv="Content‐Type" content="text/html; charset=UTF‐8">
<title>Insert title here</title>
<script type="text/javascript">
function sendRequest(){
//js的ajax访问
//1)创建Ajax引擎对象
var xmlhttp = new XMLHttpRequest();
//2)为Ajax引擎对象绑定监听(监听服务器已将数据响应给引擎)
xmlhttp.onreadystatechange=function(){//引擎状态一改变就触发该事件
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//5)接受响应数据
//获得服务器端返回给引擎对象的数据
alert(xmlhttp.responseText);
}
}
//3)绑定提交地址
/*
GET:请求方式
url地址
true是否异步 代表异步 false代表同步
*/
xmlhttp.open("GET","/AjaxDemo/ajaxServlet",true);
//4)发送请求
xmlhttp.send();
}
</script>
</head>
<body>
<input type="button" value="ajax异步访问服务器端" onclick="sendRequest()">
</body>
</html>

Servlet代码


import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//urlPatterns="/ajaxServlet"
public class AjaxServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.getWriter().write("ajax response data ...");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
}

实现效果
js原生的ajax的代码实现

相关文章:

  • 2021-11-27
  • 2022-12-23
  • 2021-12-13
  • 2022-12-23
  • 2022-12-23
  • 2022-01-02
  • 2021-11-06
猜你喜欢
  • 2022-12-23
  • 2022-01-17
  • 2022-12-23
  • 2021-07-05
  • 2021-11-27
  • 2022-12-23
  • 2021-05-30
相关资源
相似解决方案