原生Ajax请求

原生Ajax请求


原生Ajax请求指的是使用JavaScript中的XMLHttpRequest对象来进行异步HTTP请求。通过Ajax,可以在不刷新整个页面的情况下,与服务器进行数据交互,并实时更新页面内容。

1.创建对象

 var xmlhttp;
    if (window.XMLHttpRequest) {
    // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
        xmlhttp = new XMLHttpRequest()
    } else {
    // IE6, IE5 浏览器执行代码
        xmlhttp = new ActiveXObject('Microsoft.XMLHTTP')
    }

2.发送数据

xmlhttp.open(请求方式,请求的地址,是否异步)
请求的地址:协议(http https) + 主机(域名 ip(公网ip 局域网ip))+ 端口号 + 路径 + 参数 ?key=value&key=value

 xmlhttp.open('get', 'http://1.117.81.216:8087/weChat/applet/course/banner/list?number=5', true)
    xmlhttp.send()
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
            console.log(xmlhttp.response);
            console.log(JSON.parse(xmlhttp.response));
        }
    }

设置请求头
必须放在open()和send()之间

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

完整代码

<script>
    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest()
    } else {
        xmlhttp = new ActiveXObject('Microsoft.XMLHTTP')
    }
    xmlhttp.open('get', 'http://1.117.81.216:8087/weChat/applet/course/banner/list?number=5', true)
    xmlhttp.send()
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
            console.log(xmlhttp.response);
            console.log(JSON.parse(xmlhttp.response));
        }
    }
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值