AJAX即Asynchronous Javascript And XML,即异步JavaScript和XML。
AJAX作用:
- 与服务器进行数据交换:通过Ajax可以给服务器发送请求,并获取服务器响应的数据。(使用Ajax和服务器进行通信,就可以使用Html+Ajax来替换JSP页面了~)
- 异步交互:可以在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术
(通俗的说,异步请求就是不会有转圈圈等行为,让用户感知到正在处理请求~)
- 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;
-
- @WebServlet("/ajax01")
- public class Ajax_Servlet extends HttpServlet
- {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
-
- resp.setContentType("text/html;charset=UTF-8");
- resp.getWriter().write("
Ajax的初次尝试~
"); - }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- this.doGet(req, resp);
- }
- }
- var xhttp;
- xhttp= new XMLHttpRequest();
- xhttp.open("GET","http://localhost:8080/Ajax_S1_war/ajax01");
- xhttp.send();
- xhttp.onreadystatechange = function (){
- if (this.readyState==4 && this.status==200)
- {
- alert(this.responseText);
- }
注意:script标签要写在body里面!
获取成功~