1. 程式人生 > 其它 >js傳送get 、post請求

js傳送get 、post請求

前言

我們經常會用到js傳送網路請求,這裡用到XMLHttpRequest,主要是為了考慮早期的IE。分為三步:建立需要的物件、連線和傳送、接收。

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

POST請求

複製程式碼
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);
    }
};

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