Ajax 基础知识

前言

  • Ajax(Asynchronous JavaScript and XML)异步的 JavaScript 和 XML。

  • Ajax 不是新的编程语言,而是一种使用现有标准的新方法。

  • Ajax 最大的优点是在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容。

  • Ajax 不需要任何浏览器插件,但需要用户允许 JavaScript 在浏览器上执行。

  • Ajax 教程(w3cschool)

  • Ajax 教程(runoob)

  • Ajax 精修

  • Ajax 快速入门

1、Ajax

  • 通过 Ajax 实现异步刷新

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    <span>输入账号 :</span>
    <input id="name" name="name" onkeyup="check()" type="text">
    <span id="result"></span>

    <script>
    var xmlhttp;
    function check() {
    var name = document.getElementById("name").value;
    var url = "https://how2j.cn/study/checkName.jsp?name=" + name;

    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = checkResult; // 设置响应函数
    xmlhttp.open("GET", url, true); // 设置访问的页面
    xmlhttp.send(null); // 执行访问
    }

    function checkResult() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    document.getElementById('result').innerHTML = xmlhttp.responseText;
    }
    }
    </script>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isELIgnored="false"%>

    <%
    String name = request.getParameter("name");

    if ("abc".equals(name)) {
    out.print("<font color='red'>已经存在</font>");
    } else {
    out.print("<font color='green'>可以使用</font>");
    }
    %>
  • 图示

  • 解析

    • XMLHttpRequest 对象是一个 JavaScript 对象,它可以在用户没有感觉的情况下,就像背后运行的一根小线程一般,悄悄的和服务器进行数据交互,Ajax 就是通过它做到无刷新效果的。

    • 通过 open 函数设置背后的这个小线程,将要访问的页面 url,通过 send 函数进行实际的访问。

    • null 表示没有参数,因为参数已经通过 “GET” 方式,放在 url 里了。

      • 只有在用 “POST”,并且需要发送参数的时候,才会使用到 send 发送参数。
      • 类似这样:xmlhttp.send("user=" + username + "&password=" + password);
    • xmlhttp.readyState 4 表示请求已完成,xmlhttp.status 200 表示响应成功,xmlhttp.responseText 用于获取服务端传回来的文本。

2、Ajax 实例

文章目录
  1. 1. 前言
  2. 2. 1、Ajax
  3. 3. 2、Ajax 实例
隐藏目录