前言
我們經常會用到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);
}
};