AJAX入门:前端连接后端

发布于:2024-03-15 ⋅ 阅读:(66) ⋅ 点赞:(0)

一.概述

AJAX即Asynchronous Javascript And XML,即异步JavaScript和XML。

 

AJAX作用:

  1. 与服务器进行数据交换:通过Ajax可以给服务器发送请求,并获取服务器响应的数据。(使用Ajax和服务器进行通信,就可以使用Html+Ajax来替换JSP页面了~)
  2. 异步交互:可以在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术

(通俗的说,异步请求就是不会有转圈圈等行为,让用户感知到正在处理请求~)

二.写法

1.创建服务端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;

@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("<h1>Ajax的初次尝试~</h1>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

2.创建核心对象

var xhttp;
xhttp= new XMLHttpRequest();

3.发送请求

    xhttp.open("GET","http://localhost:8080/Ajax_S1_war/ajax01");
    xhttp.send();

4.获取响应

    xhttp.onreadystatechange = function (){
        if (this.readyState==4 && this.status==200)
        {
            alert(this.responseText);
        }

注意:script标签要写在body里面!

获取成功~