AJAX

什么是AJAX?

AJAX(AsynChronous JavaScript And XML):异步JavaScript和XML,是指一种创建交互式网页应用的网页开发技术
ajax是一种浏览器通过js异步发起请求,局部更新页面的技术

ajax请求的局部更新,浏览器地址栏不会发生变化,且局部更新不会舍弃原来页面的内容

 

原生JavaScript的Ajax请求

<button onclick="ajaxRequest();">ajax请求</button>

<script type="text/javascript">
    var ajaxRequest = function (){
        //1、创建XMLHttpRequest
        var request = new XMLHttpRequest();
        //2、调用open方法设置请求参数
        request.open("GET", "http://localhost:8080/myjavaweb/ajaxServlet", true);
        //4、在send方法前绑定onreadystatechange事件,处理请求完成后的操作
        request.onreadystatechange = function (){
            if (request.readyState == 4 && request.status == 200){
                alert(request.responseText);
            }
        }
        //3、调用send方法将请求发送到服务器
        request.send();
    }
</script>

  

package com.tang.web.servlet;

import com.google.gson.Gson;
import com.tang.web.servlet.bean.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AjaxServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");

        System.out.println("收到ajax请求");

        Gson gson = new Gson();
        resp.getWriter().write(gson.toJson(new User("张三", "123", "男", 25)));
    }

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

  

JQuery的Ajax请求

 

AJAX

上一篇:「HTML+CSS」--自定义加载动画【012】


下一篇:.env文件为NodeJS全局环境变量