0
点赞
收藏
分享

微信扫一扫

AJAX复习~(1)

猎书客er 2022-03-16 阅读 31

ajax

  1. 作用:在网页中不跳转的情况下,向服务器请求数据
  2. 应用:局部刷新
  3. 交互三个流程:
    • 请求(浏览器)
    • 处理(服务器)
    • 相应(服务器)

ajax的工作流程

  1. 创建XMLHttpRequest对象(俗称小黄人)
    • let xhr = new XMLHttpRequest
  2. 设置请求:
    • xhr.open('get', 'https://autumnfish.cn/api/joke');
  3. 发送请求:
    • xhr.send();
  4. .注册(响应事件)回调函数
    • 这个函数不是立即执行的,而是等服务器把数据响应返回才会执行(PS:什么时候执行取决于你的网速快慢)
    • xhr.onload = function () {console.log(xhr.responseText);}

post请求

  1. ajax发送post请求:

    1. post请求需要单独设置请求头:不需要记,固定格式

      • xhr.setRequestHeader(’Content-type‘,’application/x-www-form-urlencoded‘)
    2. post参数 在xhr.send()方法中发送

      ​ 格式: xhr.send(‘key=value’)

get和post的区别

请求方法get和post区别: 传参方式不同

get请求: 直接在url后面拼接参数

  • 参数在url中,安全性不高
 //(1).实例化ajax对象
    let xhr = new XMLHttpRequest()
    //(2).设置请求方法和地址
    //get请求的数据直接添加在url的后面 格式是 url?key=value
    xhr.open('get', '接口url')
    //(3).发送请求
    xhr.send()
    //(4).注册回调函数
    xhr.onload = function() {
      console.log(xhr.responseText)
    }

post请求:

  • 需要设置请求头(固定语法):xhr.setRequestHeader(‘Content-type’,‘application/x-www-form-urlencoded’)

  • 注意:这是固定格式,错一个字母都不行,强烈建议复制粘贴

  • 使用xhr的send方法发送参数: xhr.send(‘参数名=参数值’);

  • 注意:不要加前面的?

//(1).实例化ajax对象
    let xhr = new XMLHttpRequest()
    //(2).设置请求方法和地址
    xhr.open('post', '')
    //(3).设置请求头(post请求才需要设置)
    xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
    //(4).发送请求 : 参数格式  'key=value' 
    xhr.send('key=value')
    //(5).注册回调函数
    xhr.onload = function () {
      console.log(xhr.responseText)
    }
举报

相关推荐

0 条评论