• ajax简介


    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 属性

  • 相关阅读:
    Microsoft office 2013安装图解
    6.2单一继承
    #include <QLabel>
    #include <QDebug>
    9.1运算符重载
    简单QT界面信号图形化输入输出
    类指针引用
    NULL和nullptr的区别
    网易云课堂_C语言程序设计进阶_第8周:图形交互程序
    5.3友元函数
  • 原文地址:https://www.cnblogs.com/ysmdbk/p/11459731.html
Copyright © 2020-2023  润新知