初识Ajax

2018-11-11  本文已影响0人  lassiey

一、ajax是什么?

1、Asynchronous JavaScript & XML
2、web开发的一种技术
3、异步发送&请求数据
4、不需要重新刷新当前页面
5、目前JSON数据格式已经占据市场

二、ajax工作流程

ajax工作过程图.png

客户端即我们的浏览器。简单来说,ajax的工作流程就是客户端向服务器发送一个请求,服务器给予一个响应。但实际上会经过很多的步骤,如上图右侧的部分所示。

1、XmlHttpRequest对象

1、对象类型的API
2、在浏览器环境下使用
3、用于客户端和服务端数据的传递和接收
4、用于请求XML数据(JSON,纯文本text)

2、其它类似技术/库

jQuery、Axios、Superagent、Fetch API、Prototype、Node HTTP

3、请求纯文本

<!DOCTYPE html>
<html>
<head>
    <title>Ajax 1 - 请求纯文本</title>
</head>
<body>
    <button id="button">请求纯文本</button>

    <script type="text/javascript">
        document.getElementById('button').addEventListener("click",loadText);

        function loadText() {
            //console.log("hello world!");
            //创建XMLHttpRequest对象
            var xhr = new XMLHttpRequest();
            //console.log(xhr);
            //open(type,url/file,async)
            xhr.open('GET','sample.txt',ture);

            //两种方式请求 onload / onreadystattechange
            xhr.onload = function(){
                console.log(this.responseText);
            }
            // xhr.onreadystattechange = function(){
            //  console.log(this.responseText);
            // }
            //发送请求
            xhr.send();
        }
    </script>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读