Ajax入门

一、Ajax简介

以前,我们访问浏览器页面时,都是整页刷新的。

有时候,没有必要整页的数据都刷新,只需要一部分的数据刷新即可。

1、 Ajax全称

 Ajax全称:Asynchronous JavaScript and XML异步的JavaScript和XML

2、 XML介绍

以前,异步交互的格式,都是用XML格式。

如:

<fruit>
    <name>apple</name>
    <weight>0.5kg</weight>
    <color>red</color>
</fruit>

3、Json介绍

现在,主流的格式,是Json格式。

如:

{
    "fruit" : {
        "name" : "apple",
        "weight" : "0.5kg",
        "color" : "red"
    }
}

4、Ajax优缺点

(1)优点:

按需获取数据,提升系统性能。

(2)缺点:

异步获取数据,不利于搜索引擎优化。

二、Ajax原理

1、思考:之前我们是如何向服务器发送请求的?

(1)在浏览器中直接输入网址

(2)a标签,实现页面跳转

(3)表单提交

(4)Postman模拟http请求

 2、XMLhttpRequest对象

(1)基本介绍

server.js:

const Koa = require("koa");
const router = require("koa-router")();
const nunjucks = require("nunjucks");
const views = require("koa-views");
const parser = require("koa-parser");
const app = new Koa();

app.use(views(__dirname + "/views", {
    map: {
        html: "nunjucks"
    }
}))

app.use(parser());

router.get("/", async ctx => {
    await ctx.render("index");
})

// 点击按钮时,触发事件
router.get("/data", async ctx => {
    ctx.body = "hello world";
})


app.use(router.routes());

// 设置监听端口
app.listen(3000, () => {
    console.log("server is running");
})

index.html:

<body>
    <h1>首页</h1>
    <button>获取数据</button>
    <script>
        document.querySelector("button").onclick = function () {
            // 创建XMLHttpRequest对象
            let xhr = new XMLHttpRequest();
            // open可以用来规定请求的类型
            xhr.open("get","/data");
            // 发送请求
            xhr.send();
        }
    </script>
</body>

 效果:

点击按钮时,获取到了:xhr对象发送过来的数据。 

(2) onreadystatechange

<body>
    <h1>首页</h1>
    <button>获取数据</button>
    <script>
        document.querySelector("button").onclick = function () {
            // 创建XMLHttpRequest对象
            let xhr = new XMLHttpRequest();
            // open可以用来规定请求的类型
            xhr.open("get", "/data");
            // 发送请求
            xhr.send();

            // 该事件监听readyState的变化
            xhr.onreadystatechange = function () {
                // 0:请求未初始化
                // 1:服务器连接已建立
                // 2:请求已接收
                // 3:请求处理中
                // 4:请求已完成,且响应已就绪
                if (xhr.readyState === 4 && xhr.status === 200) {
                    alert(xhr.responseText);
                }
            }
        }
    </script>
</body>

效果:点击按钮时,弹出hello world。

三、 使用回调方式,获取到xhr.responseText

使用return(同步)的话,没法获取异步的数据。

<body>
    <h1>首页</h1>
    <button>获取数据</button>
    <script>
        document.querySelector("button").onclick = function () {
            // 使用回调,获取到res
            myajax("get", "/data", function (res) {
                alert(res);
            });
        }

        // 自定义ajax
        function myajax(method, url, next) {
            let xhr = new XMLHttpRequest();
            xhr.open(method, url);
            xhr.send();
            let result = "";
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    next(xhr.responseText);
                }
            }
            return result;
        }
    </script>
</body>

 

但是,程序如果大量使用回调函数的话,就会变得难维护。 

四、使用Promise对象,获取xhr.responseText

<body>
    <h1>首页</h1>
    <button>获取数据</button>
    <script>
        document.querySelector("button").onclick = function () {
            // 使用回调,获取到res
            myajax("get", "/data").then(res => {
                console.log("jinlai")
                alert(res);
            });
        }

        // 自定义ajax
        function myajax(method, url) {
            return new Promise(function (resolve) {
                let xhr = new XMLHttpRequest();
                xhr.open(method, url);
                xhr.send();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        resolve(xhr.responseText);
                    }
                }
            })
        }
    </script>
</body>

五、总结

这样写太麻烦了,以后工作中,用ajax,都是用封装好的第三方库

比如:jQuery等...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pro1822

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值