• 原生js发送Ajax请求


    一、通过onload注册事件

    // 1. 创建一个 xhr 对象
    var xhr = new XMLHttpRequest();
    // 2. 设置请求的方式和路径
    xhr.open('GET', '/time');
    // 3. 发送请求
    xhr.send(null);
    // 4. 注册事件
    xhr.onload = function () {
        // 通过 xhr 的 responseText 获取到响应的响应体
       console.log(this.responseText)
    }

      注意:如果是发送post方式的请求,需要在open和send中间设置请求头,send中添加要传递的参数(有格式要求:=连接属性和值;&连接不同的属性)。

    var xhr = new XMLHttpRequest()
    xhr.open('POST', '/query-post')
    // 设置 Content-Type 为 application/x-www-form-urlencoded,这行代码不用死记硬背,去复制即可
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
    // 需要提交到服务端的数据可以通过 send 方法的参数传递
    // 格式:name=zhangsan&age=18
    xhr.send('name=zhangsan&age=18')
    xhr.onload = function () {
        console.log(this.responseText)
    }

    二、通过onreadystatechange注册事件

      onload 是 HTML5 以后新增的方便获取响应的事件,过去获取浏览器返回内容的时候使用的是 onreadystatechange。

    var xhr = new XMLHttpRequest()
    // open 方法的第一个参数的作用就是设置请求的 method
    xhr.open('POST', '/query-post')
    // 设置 Content-Type 为 application/x-www-form-urlencoded,这行代码不用死记硬背,去复制即可
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
    // 需要提交到服务端的数据可以通过 send 方法的参数传递
    // 格式:name=zhangsan&age=18
    xhr.send('name=zhangsan&age=18')
    // 更改事件为onreadystatechange
    xhr.onreadystatechange = function () {
        if (this.readyState === 4) {
        // 后续逻辑......
      }
    } 

     

  • 相关阅读:
    ObjectiveC 语言入门教程 | MacCocoa
    Neopythonic memcached cliend
    python Preventing django from appending "_id" to a foreign key field Stack Overflow
    JQuery and python script | python | PyMantra
    Import error on django models.py
    如何成为Python高手 技术讨论 云计算开发者社区 Powered by Discuz!
    [Hadoop] 实际应用场景之 百度 Zhu_Julian's Notes (朱显杰的技术博客) 博客频道 CSDN.NET
    DjangoResources – Django
    hue
    Huseyin Yilmaz
  • 原文地址:https://www.cnblogs.com/belongs-to-qinghua/p/11353114.html
Copyright © 2020-2023  润新知