JS原生:XMLHttpRequest发送GET&POST请求

目录

1、XMLHttpRequest   (xhr)

2、使用xhr发起GET无参请求

3、使用xhr发起GET有参请求

4、使用xhr发起POST请求


学到了xhr发起GET和POST请求,在此记录一下

1、XMLHttpRequest   (xhr)

XMLHttpRequest(简称xhr)是浏览器提供的JavaScript对象,通过它,可以 请求服务器上的数据资源

在jQuery中封装的AJAX函数,就是基于xhr,然后封装出jq中的ajax,然后就可以调用出get、post、ajax()三个方法

在原生中实际上真正用到的,是XMLHttpRequest这个对象

2、使用xhr发起GET无参请求

四个步骤:

①:创建 xhr对象

     //1、创建一个 xhr 的对象
     let xhr = new XMLHttpRequest()

②:调用 xhr的open()函数(open中传递两个参数,参数一是GET/POST请求方式,参数二是请求的URL地址)

     //2、调用xhr中的open()函数,创建一个Ajax的请求
     xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')

③:调用 xhr.send()函数

     //3、调用xhr的send函数,发起请求
     xhr.send()

④:监听 xhr.onreadystatechange事件

     //4、监听 onreadystatechange 事件
     xhr.onreadystatechange = function () {
         if (xhr.readyState === 4 && xhr.status === 200) {  //固定写法
             //数据获取成功,获取服务器响应的数据 
             console.log(xhr.responseText)
         }
     }

xhr发起GET请求的完整代码

 <script>
     //1、创建一个 xhr 的对象
     let xhr = new XMLHttpRequest()
     //2、调用xhr中的open()函数,创建一个Ajax的请求
     xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')
     //3、调用xhr的send函数,发起请求
     xhr.send()
     //4、监听 onreadystatechange 事件
     xhr.onreadystatechange = function () {
         if (xhr.readyState === 4 && xhr.status === 200) {  //固定写法
             //数据获取成功,获取服务器响应的数据 
             console.log(xhr.responseText)
         }
     }
 </script>

xhr 对象的 readyState 属性

XHR对象中的 readyState 属性,用来表示 当前Ajax请求所处的状态

每个Ajax请求必然处于以下状态的一个:

状态描述
0UNSENTxhr对象已被创建,但未调用open方法
1OPENEDopen()方法已经被调用
2HEADERS_RECEIVEDsend()方法已被调用,响应头也已经被接收
3LOADING数据接收中,此时 response 属性中已经包含部分数据
4DONEAjax请求完成,这意味着数据传输已经彻底 完成失败

3、使用xhr发起GET有参请求

使用 xhr对象发起带参数的请求,只需要在 调用open()方法期间,为URL地址指定参数即可

代码示例

xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks?id=1')

这里在URL后用 ? 进行连接参数,用键值对的方式,=号左边的是键,右边是值,其余与无参GET一致

这种在URL地址后拼接的参数?+参数 叫做 查询字符串

如果有多个参数传递,参数与参数之间使用 & 符号连接

 let xhr = new XMLHttpRequest()

        //不带参数的URL地址
        xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')

        //带一个参数的URL地址
        xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks?id=1')

        //带二个参数的URL地址
        xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks?id=1&bookname=西游记')

4、使用xhr发起POST请求

步骤(五步):

①、创建 xhr 对象

        //1、创建xhr的对象
        let xhr = new XMLHttpRequest()

②、调用 xhr.open() 函数

        //2、调用open函数('请求类型','url')
        xhr.open('POST', 'http://www.liulongbin.top:3006/api/addbook')

③、xhr.setRequestHeader 设置 Content-Type 属性(固定写法)

Content-Type必须写在open()的下面,且语句是固定的

        //3、设置 Content-Type属性(固定写法)
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')

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

        //4、调用send函数
        xhr.send('bookname=落日听风&author=我我我&publisher=个人出版社')

⑤、监听 xhr.onreadystatechange事件

        //5、监听事件
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                console.log(xhr.responseText)
            }
        }

⑥、完整的POST请求

    <script>
        //1、创建xhr的对象
        let xhr = new XMLHttpRequest()
        //2、调用open函数('请求类型','url')
        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>

  • 6
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 使用XMLHttpRequest对象可以实现get和post请求:// get请求 var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://www.example.com/data.json', true); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ console.log(xhr.responseText); } } } xhr.send();// post请求 var xhr = new XMLHttpRequest(); xhr.open('POST', 'http://www.example.com/data.json', true); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ console.log(xhr.responseText); } } } xhr.send('data=test'); ### 回答2: 要使用原生JavaScript来实现GET和POST请求,可以使用XMLHttpRequest对象进行数据的发送和接收。 GET请求的实现可以按照以下步骤进行: 1. 创建XMLHttpRequest对象:使用"new XMLHttpRequest()"来创建一个新的XMLHttpRequest对象。 2. 设置请求的方法和URL:使用open()方法设置请求的方法为"GET",并指定请求的URL。 3. 发送请求:使用send()方法发送请求。对于GET请求,可以将参数以字符串形式加在URL的末尾。 4. 监听响应状态变化:使用onreadystatechange属性来监听XMLHttpRequest对象的状态变化,判断是否接收到了响应。 5. 处理响应:在状态值为4且响应状态码为200时,表示请求成功,可以通过responseText属性获取响应的内容。 以下是一个简单的GET请求的示例代码: ```javascript let xhr = new XMLHttpRequest(); xhr.open('GET', 'https://api.example.com/data', true); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send(); ``` POST请求的实现相对复杂一些,需要在发送请求前设置请求头和请求体的内容。可以按照以下步骤进行: 1. 创建XMLHttpRequest对象:同样使用"new XMLHttpRequest()"来创建一个新的XMLHttpRequest对象。 2. 设置请求的方法和URL:使用open()方法设置请求的方法为"POST",并指定请求的URL。 3. 设置请求头:使用setRequestHeader()方法设置请求头的内容,例如设置"Content-Type"为"application/json"。 4. 设置请求体:使用send()方法发送请求体的内容,以字符串形式传递参数和数据。 5. 监听响应状态变化:同样使用onreadystatechange属性来监听XMLHttpRequest对象的状态变化,判断是否接收到了响应。 6. 处理响应:在状态值为4且响应状态码为200时,表示请求成功,可以通过responseText属性获取响应的内容。 以下是一个简单的POST请求的示例代码: ```javascript let xhr = new XMLHttpRequest(); xhr.open('POST', 'https://api.example.com/data', true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }; xhr.send(JSON.stringify({ key1: 'value1', key2: 'value2' })); ``` 以上就是用原生JavaScript实现GET和POST请求的简单示例。实际应用中,还可以根据需要添加错误处理、参数处理等功能。 ### 回答3: 使用JavaScript原生实现GET请求可以通过创建一个XMLHttpRequest对象,并使用open()方法指定请求的方法和URL,例如: ```javascript let xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example.com/api/data', true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { // 请求成功 let response = JSON.parse(xhr.responseText); console.log(response); } }; xhr.send(); ``` 上述代码创建了一个GET请求,URL为http://example.com/api/data,回调函数onreadystatechange会在readyState为4(请求已完成)且status为200(成功)时执行。在回调函数中可以处理服务器返回的数据。 使用JavaScript原生实现POST请求也是通过创建XMLHttpRequest对象,但需要使用send()方法发送请求数据,并设置合适的请求头。例如: ```javascript let xhr = new XMLHttpRequest(); xhr.open('POST', 'http://example.com/api/data', true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { // 请求成功 let response = JSON.parse(xhr.responseText); console.log(response); } }; let data = {name: 'John', age: 25}; xhr.send(JSON.stringify(data)); ``` 上述代码创建了一个POST请求,URL为http://example.com/api/data,并设置请求头Content-Type为application/json表示发送的数据为JSON格式。请求体数据需要通过JSON.stringify()方法将对象转换为字符串,然后通过send()方法发送。同样,在回调函数中可以处理服务器返回的数据。 这些是使用JavaScript原生实现GET和POST请求的简单示例,可以根据具体的需求和使用场景进行灵活调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长风沛雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值