【web】 js发送get 、post请求的方法简介(Content-Type作用)

1. 使用XMLHttpRequest创建请求

主要分三步:

  • 第一步:创建需要的对象,这里主要用到的是XMLHttpRequest,注意需要考虑早期的IE;

  • 第二步:连接和发送;

  • 第三步:接收;

1.1 GET请求:

var httpRequest = new XMLHttpRequest();//第一步:建立所需的对象
        httpRequest.open('GET', 'url', true);//第二步:打开连接  将请求参数写在url中  ps:"./Ptest.php?name=test&nameone=testone"
        httpRequest.send();//第三步:发送请求  将请求参数写在URL中
        /**
         * 获取数据后的处理程序
         */
        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState == 4 && httpRequest.status == 200) {
                var json = httpRequest.responseText;//获取到json字符串,还需解析
                console.log(json);
            }
        };

不过需要注意的是,一般get请求不需要设置Content-Type,只有post才有必要设置!

具体原因可参见:《Http请求中请求头Content-Type讲解》

1.2 POST请求:

POST请求请求需要设置Content-Type,更多的可选项参见《Http请求中请求头Content-Type讲解》

发送普通文本:

var httpRequest = new XMLHttpRequest();//第一步:创建需要的对象
httpRequest.open('POST', 'url', true); //第二步:打开连接
httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");//设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头)
httpRequest.send('name=teswe&ee=ef');//发送请求 将情头体写在send中
/**
 * 获取数据后的处理程序
 */
httpRequest.onreadystatechange = function () {//请求后的回调接口,可将请求成功后要执行的程序写在其中
    if (httpRequest.readyState == 4 && httpRequest.status == 200) {//验证请求是否发送成功
        var json = httpRequest.responseText;//获取到服务端返回的数据
        console.log(json);
    }
};

send方法的入参是普通字符串!

post方式发送json:

var httpRequest = new XMLHttpRequest();//第一步:创建需要的对象
httpRequest.open('POST', 'url', true); //第二步:打开连接/***发送json格式文件必须设置请求头 ;如下 - */
httpRequest.setRequestHeader("Content-type","application/json");//设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头)var obj = { name: 'zhansgan', age: 18 };
httpRequest.send(JSON.stringify(obj));//发送请求 将json写入send中
/**
 * 获取数据后的处理程序
 */
httpRequest.onreadystatechange = function () {//请求后的回调接口,可将请求成功后要执行的程序写在其中
    if (httpRequest.readyState == 4 && httpRequest.status == 200) {//验证请求是否发送成功
        var json = httpRequest.responseText;//获取到服务端返回的数据
        console.log(json);
    }
};

send方法的入参是json格式的数据!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值