原生js發(fā)送ajax請求
4步:
//1. 實例化xhr對象
var xhr = new XMLHttpRequest();
//2. 調用open方法準備ajax請求
//參數(shù)1: 請求方式 (get、post、delete、put)
//參數(shù)2: 請求的服務器端的地址
//參數(shù)3: true(異步、默認)、false(同步)
xhr.open('get', '/getData');
//3. 調用send方法發(fā)送ajax請求
xhr.send();
//4. 調用onload事件,配合responseText來接收服務器端返回的數(shù)據(jù)
// xhr.responseText: 以字符串形式來接收服務器端返回的結果
// 服務器端返回的數(shù)據(jù)有兩種可能:
// 1) 普通字符串(hello world \ I am xiaoming)
// 2) json字符串('{"id":"101", type:"goods", "name":"小米"}')
// json字符串都會使用 JSON.parse 轉回成對象形式
xhr.onload = function () {
xhr.responseText
}
發(fā)送請求時get傳參
get參數(shù)要拼接在url地址的后面,以?進行分割
var xhr = new XMLHttpRequest();
//參數(shù)2的位置用來拼接get參數(shù), 以 ? 作為分隔符
// ?之前: 請求的url地址
// ?之后: 查詢參數(shù) key1=value1&key2=value2&...
xhr.open('get', '/getData?id=1&name=zs&age=20&...');
xhr.send();
xhr.onload = function () {
xhr.responseText
}
發(fā)送請求時post傳參
post傳參有三種方式: key=value&key=value&... FormData json字符串
//1. key=value&key=value&...
// application/x-www-form-urlencoded : 需要key=value這種結構的參數(shù)
var xhr = new XMLHttpRequest();
xhr.open('post', '/postData');
//將發(fā)送到服務器端的數(shù)據(jù)寫成一個字符串
var str = 'id=1&name=zs&age=20&...'
//發(fā)送請求之前一定要設置請求頭為 application/x-www-form-urlencoded
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
xhr.send(str);
xhr.onload = function () {
xhr.responseText
}
//2. 發(fā)送FormData類型的數(shù)據(jù)
//1) 直接獲取整個post表單的數(shù)據(jù)
var fm = document.querySelector('form');
var fd = new FormData(fm)
//2) 實例化一個空的FormData,再向里面append數(shù)據(jù)
var fd = new FormData();
fd.append('name', 'xiaoming');
fd.append('age', 20);
fd.append('img', this.files[0]);
//發(fā)送ajax請求時,如果發(fā)送到服務器端的數(shù)據(jù)為FormData時,不需要設置請求頭,需要將fd作為參數(shù)傳入send
var xhr = new XMLHttpRequest();
xhr.open('post', '/postData');
xhr.send(fd);
xhr.onload = function () {
xhr.responseText
}
//3. 發(fā)送到服務器端的數(shù)據(jù)是json字符串
var jsonStr = JSON.stringify({name:"zs", age:20}); //'{name:"zs", age:20}'
var xhr = new XMLHttpRequest();
xhr.open('post', '/postData');
xhr.setRequestHeader('content-type', 'application/json');
xhr.send(jsonStr);
xhr.onload = function () {
xhr.responseText
}
|