原生AJAX请求


前言

ajax 即 Asynchronous Javascript And XML,AJAX 不是一门的新的语言,而是对现有持术的综合利用。本质是在 HTTP 协议的基础上以异步的方式与服务器进行通信.


提示:以下是本篇文章正文内容,下面案例可供参考

一、AJAX五部曲

1.创建一个异步对象xmlhttp;

var xhr= new XMLHttpRequest(); 
new ActiveXObject("Microsoft.XMLHTTP"); //IE6以下

2.调用open方法设置请求方式和请求地址;

xhr.open(type,url);

3.设置请求头(post需要)

xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 

4.监听请求完成函数

   xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4 && xhr.status == 200) {

                    }
                }

通过onreadystatechange 事件来监听发送的状态变化,readyState状态为4时,.status为200请求结束成功

5.发送请求

xhr.send();

其中post请求方式传参数,直接写在send()里面,get请求参数则需要放在url地址的参数中。并通过urlencode的方式传参,也就是?隔开url和参数,然后多个参数用&连接,参数格式为:key=val。


二、案例

调用某易源的笑话接口:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .boss {
            width: 300px;
            height: 300px;
            /* border: 1px solid red; */
            text-align: center;
            float: left;
        }
        
        .boss img {
            width: 300px;
            height: 300px;
        }
    </style>
</head>

<body>
    <!-- <div class="boss">
        <img src="img/0.jpg" alt="">
    </div> -->
</body>
<script>
    var str = "";
    var xhr = new XMLHttpRequest();
    xhr.open("get", "https://route.showapi.com/341-2?showapi_appid=124345&showapi_sign=87510e6b80b0408e9f623f9c00ad1c7a&page=1&maxResult=20")
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log(JSON.parse(xhr.response));
            var list = JSON.parse(xhr.response)["showapi_res_body"].contentlist;
            console.log(list);
            for (var i = 0; i < list.length; i++) {
                str += `
                <div class="boss">
            
                    <img src="${list[i]["img"]}" alt="">
                </div>
                `
            }

            document.body.innerHTML += str;
        }
    }
    xhr.send();
</script>

</html>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值