原生ajax 设置get请求参数和请求头信息和发送 post请求

get请求发送参数直接在路径后面加问号即可

  xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=50');

设置请求头信息

1.请求头中本来就有这个属性,只是修改该属性的值

xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

2.在请求头中设置自己的属性

 需要在服务器的.js中添加一句(开启接受所有类型的头信息)

 response.setHeader('Access-Control-Allow-headers','*');

开启之后再用.html发送请求,会发现除了要发送的请求外,还有一个请求跟着发送了,这个请求的请求方式是options,作用是告诉服务器主请求的请求头是安全的,

但是服务器还没有设置接收optins类型的请求的方法,需要弄一个接收所有类型请求的方法

// 引入express
const express =require('express');
// 2.创建应用对象
const app =express();

// 3.创建路由规划
// request 是对请求报文的封装
// response是对响应报文的封装
// 要在后面输入server才可访问http://localhost:8000/server
app.get('/server',(request,response)=>{
    response.setHeader('Access-Control-Allow-Origin','*');
    response.setHeader('Access-Control-Allow-headers','*');
    // 设置响应
    response.send('hello  express');
});
app.all('/server',(request,response)=>{
    response.setHeader('Access-Control-Allow-Origin','*');
    // 接受所有请求的头信息
    response.setHeader('Access-Control-Allow-headers','*');
    // 设置响应
    response.send('hello  express');
});
app.listen(8000,()=>{
    console.log("服务已经启动,8000端口监听中");
})

 弄好之后就可以在主请求中发现这个属性了

设置post请求

 把这两个地方添加或者修改即可发送post请求

    设置post请求的请求体       xhr.send('a:10&b=20');

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #id{
            width: 200px;
            height: 200px;
        }
    </style>
</head>
<body>
    <textarea id="result"></textarea>

</body>
<script>
    const result=document.getElementById("result");
    // result.addEventListener("mouseover",function() {
    //    console.log("test");
    // });
     result.onmouseover=function(e)
     {  //  1.创建对象
         const xhr =new XMLHttpRequest();
        //  2.设置请求类型和url
        xhr.open('POST','http://127.0.0.1:8000/server');
        //这是请求头中本来就有的属性
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        //这是请求头中自己新建的属性,需要在服务器中加一句,看下面
        xhr.setRequestHeader('hxut','zyk');
        //  3.发送
        xhr.send('a:10&b=20');
        // 4.判断请求状态
        xhr.onreadystatechange=function(){
            if(xhr.status===4){
                if(xhr.status>200&xhr.status>300){
                    console.log(xhr.status);//输出状态码
                }
            }
            result.innerHTML=xhr.response;
            console.log(xhr.response)
        }
       
     }
</script>
</html>

https://gitee.com/rjgc1192/ajax/tree/master/day01      版本号是0025d44

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值