AJAX入门:前端连接后端-LMLPHP

一.概述

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

AJAX入门:前端连接后端-LMLPHP 

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

二.写法

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里面!

AJAX入门:前端连接后端-LMLPHP

获取成功~

03-15 22:05