js http请求

 

 

 

 基本用法

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

 

同步用法

let mHttp = (method, url, data, dataType) => {
            let httpRequest = new XMLHttpRequest();//第一步:创建需要的对象
                if (method === "GET"){
                    if (Object.keys(data).length !== 0 && url.indexOf("?") === -1){
                        url += "?"
                    }else {
                        url += "&"
                    }
                    for (let key in data) {
                        url += key + "=" + data[key]
                    }
                }

                httpRequest.open(method, url);
                try{
                    if ('{{ csrf_token }}'){
                        httpRequest.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");//设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头)
                    }
                }catch (e) {}

                if (dataType === "json"){
                    httpRequest.setRequestHeader("Content-type", "application/json;charset=UTF-8");//设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头)
                    httpRequest.send(JSON.stringify(data));//发送请求 将json写入send中
                }
                else if (method === "POST"){
                    httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");//设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头)
                    httpRequest.send(encodeURI(JSON.stringify(data)));//发送请求 将json写入send中
                }
                else {
                    httpRequest.send();//发送请求 将json写入send中
                }


            return new Promise((resolve, reject) => {
                httpRequest.onreadystatechange = () => {//请求后的回调接口,可将请求成功后要执行的程序写在其中
                    if (httpRequest.readyState === 4 && httpRequest.status === 200) {//验证请求是否发送成功
                        let json = JSON.parse(httpRequest.responseText);//获取到服务端返回的数据
                        resolve(json)
                    }
                };
            });
        };

 

posted @ 2020-12-23 13:40  陨落&新生  阅读(3278)  评论(0编辑  收藏  举报