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)
                    }
                };
            });
        };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM