Ajax之XMLHttpRequest的基本使用

XMLHttpRequest是浏览器提供的JS对象,可以请求服务器上传的数据资源

一.使用xhr发起GET请求

一般分为四个步骤:

1.创建xhr对象

2.调用xhr.open()函数

3.调用xhr.send()函数

4.监听xhr.onreadystatechange事件

<script>
        // 1. 创建 XHR 对象
        var xhr = new XMLHttpRequest();
        // 2. 调用 open 函数
        xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')
            // 3. 调用 send 函数
        xhr.send();
        // 4. 监听 onreadystatechange 事件
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                //获取服务器响应的数据
                console.log(xhr.responseText);
            }
        }
    </script>

二.xhr对象的readyState属性

 三.使用xhr发起带参数的GET请求

 四.查询字符串

 GET请求携带参数的本质

<script>
    $.ajax({
      method: 'GET',
      url: 'http://www.liulongbin.top:3006/api/getbooks',
      data: {
        id: 1,
        bookname: '西游记'
      },
      success: function (res) {
        console.log(res)
      }
    })
  </script>

 

五.URL编码与解码

原则:使用英文字符去表示非英文字符

对其进行编码和解码分别是encodeURL( )编码的函数,decodeURL( )解码的函数。

<script>
    var str = '黑马程序员'
    var str2 = encodeURI(str)
    console.log(str2)

    console.log('----------')
    var str3 = decodeURI('%E9%BB%91%E9%A9%AC')
    console.log(str3)
  </script>

六.使用xhr发起POST请求

六步:

1.创建xhr对象

2.调用xhr.open()函数

3.设置Content-Type函数(固定写法)

4.调用xhr.send()函数,同时指定要发送的数据

5.监听xhr.onreadystatechange事件

<script>
        // 1. 创建 xhr 对象
        var xhr = new XMLHttpRequest();
        // 2. 调用 open 函数
        xhr.open('POST', 'http://www.liulongbin.top:3006/api/addbook');
        // 3. 设置 Content-Type 属性
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        // 4. 调用 send 函数
        xhr.send('bookname=水浒传&author=施耐庵&publisher=上海图书出版社');
        // 5. 监听事件
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                console.log(xhr.responseText);
            }
        }
    </script>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值