借助 XMLHttpRequest 對象
1、新建對象
2、建立連接
3、發送請求
4、查看請求狀態,接收返回數據
發送 get 請求:
var xhr = new XMLHttpRequest();//第一步:新建對象 xhr.open('GET', 'url', true);//第二步:打開連接 將請求參數寫在url中 xhr.send();//第三步:發送請求 將請求參數寫在URL中 /** * 獲取數據后的處理程序 */ xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { var res = xhr.responseText;//獲取到json字符串,解析 } };
發送 post 請求:
var xhr = new XMLHttpRequest();//第一步:新建對象 xhr.open('POST', 'url', true); //第二步:打開連接 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");//設置請求頭 注:post方式必須設置請求頭(在建立連接后設置請求頭) xhr.send('name=teswe&ee=ef');//發送請求 將情頭體寫在send中 /** * 獲取數據后的處理程序 */ xhr.onreadystatechange = function () {//請求后的回調接口,可將請求成功后的邏輯 if (xhr.readyState == 4 && xhr.status == 200) {//驗證請求是否發送成功 var res = xhr.responseText;//獲取到服務端返回的數據 } };
post 請求發送 json 數據:
var xhr = new XMLHttpRequest();//第一步:新建對象 xhr.open('POST', 'url', true); // 建立連接 xhr.setRequestHeader("Content-type","application/json");//設置請求頭 注:post方式必須設置請求頭(在建立連接后設置請求頭) var obj = { name: 'zhansgan', age: 18 }; xhr.send(JSON.stringify(obj));//發送請求 將json寫入send中 /** * 獲取數據后的處理程序 */ xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { // 代碼邏輯 } };