首页 > 技术文章 > ajax简介

ysmdbk 2019-09-04 16:08 原文

AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。

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

原生JS的实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        function loadXMLDoc()
        {
            // 2、创建一个XMLHttpRequest对象
            var xmlhttp;
            if (window.XMLHttpRequest)
            {
                //  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
                xmlhttp=new XMLHttpRequest();
            }
            else
            {
                // IE6, IE5 浏览器执行代码
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            //3、注册回调函数
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
                }
            }
            // 4、配置请求信息
            xmlhttp.open("GET","/springboot/src/main/webapp/123.txt",true);
            xmlhttp.send();
            // 5、state change发生改变调用回调函数 回调函数将xmlhttp.responseText内容写入到页面
        }
    </script>
</head>
<body>
<div id="myDiv"><h2>使用 AJAX 修改该文本内容</h2></div>
<!--1、点击按钮触发loadXMLDoc这个方法-->
<button type="button" onclick="loadXMLDoc()">修改内容</button></body>
</html>

根据上面的代码解释下ajax的请求步骤

1、点击按钮触发loadXMLDoc这个方法

  这个没啥好说的

2、创建一个XMLHttpRequest对象

   所有现代浏览器均支持 XMLHttpRequest 对象(IE5 和 IE6 使用 ActiveXObject)。XMLHttpRequest 用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

3、注册回调函数

  

4、配置请求信息

  xmlhttp.open()参数:

  • method:请求的类型;GET 或 POST
  • url:文件在服务器上的位置
  • async:true(异步)或 false(同步)

    如果是同步执行,不需要重写onreadystatechange函数,把代码放到 send() 语句后面即可

xmlhttp.open("GET","test1.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

  xmlhttp.send();

  • string:仅用于 POST 请求

    如果post请求中有参数需要卸载send方法中

xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Bill&lname=Gates");

5、state change发生改变调用回调函数 回调函数将xmlhttp.responseText内容写入到页面

  如果返回的内容是字符串(json) 使用:responseText

  如果来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,请使用 responseXML 属性

 

推荐阅读