AJAX(4)——XMLHttpRequest

发布于:2024-08-25 ⋅ 阅读:(127) ⋅ 点赞:(0)

XMLHttpRequest

定义:XMLHttpRequest(XHR)对象用于与服务器交互。通过XMLHttpRequest可以在不刷新页面的情况下请求特定URL,获取数据。这允许网页在不影响用于操作的情况下,更新页面的局部内容。XMLHttpRequest在AJAX编程中被大量使用

关系:axios内部采用XMLHttpRequest与服务器交互


使用XMLHttpRequest

步骤:

  1. 创建XMLHttpRequest对象
  2. 配置请求方法和请求URL地址
  3. 监听loadend事件,接收响应结果
  4. 发起请求
<body>
  <script>
    const xhr = new XMLHttpRequest()
    //配置请求地址
    xhr.open('GET', 'http://hmajax.itheima.net/api/province')
    //监听loadend,接收响应结果
    xhr.addEventListener('loadend', () => {
      console.log(xhr.response);   获取响应数据
      const data = JSON.parse(xhr.response)    //转换为对象
      console.log(data.list);

    })
    //发起请求
    xhr.send()
  </script>

查询参数 

语法:

http://xxx.com/xxx/xxx?参数名=值1&参数名=值2

    const xhr = new XMLHttpRequest()
    xhr.open('GET', 'http://hmajax.itheima.net/api/city?pname=辽宁省')
    xhr.addEventListener('loadend', () => {
      console.log(xhr.response);
    })
    xhr.send()

 

 XMLHttpRequest数据提交

请求头设置Content-Type:application/json

请求体携带JSON

 

    //XHR数据提交
    document.querySelector('.btn').addEventListener('click', () => {
      const xhr = new XMLHttpRequest()
      xhr.open('POST', 'http://hmajax.itheima.net/api/register')
      xhr.addEventListener('loadend', () => {
        console.log(xhr.response);

      })

      //设置请求头
      xhr.setRequestHeader('Content-Type', 'application/json')
      const obj = {
        username: 'itheima908',
        password: '765421'
      }
      const str = JSON.stringify(obj)
      //设置请求体,发送请求
      xhr.send(str)
    })