原生ajax發送數據,以及不用的方法發送


原生js發送ajax請求

4步:

//1. 實例化xhr對象
var xhr = new XMLHttpRequest();

//2. 調用open方法准備ajax請求
//參數1: 請求方式 (get、post、delete、put)
//參數2: 請求的服務器端的地址
//參數3: true(異步、默認)、false(同步)
xhr.open('get', '/getData');

//3. 調用send方法發送ajax請求
xhr.send();

//4. 調用onload事件,配合responseText來接收服務器端返回的數據
// xhr.responseText: 以字符串形式來接收服務器端返回的結果
// 服務器端返回的數據有兩種可能:
//  1) 普通字符串(hello world \ I am xiaoming)
//  2) json字符串('{"id":"101", type:"goods", "name":"小米"}')
//     json字符串都會使用 JSON.parse 轉回成對象形式
xhr.onload = function () {
    xhr.responseText
}


發送請求時get傳參

get參數要拼接在url地址的后面,以?進行分割

var xhr = new XMLHttpRequest();

//參數2的位置用來拼接get參數, 以 ? 作為分隔符
// ?之前: 請求的url地址
// ?之后: 查詢參數 key1=value1&key2=value2&...
xhr.open('get', '/getData?id=1&name=zs&age=20&...');

xhr.send();

xhr.onload = function () {
    xhr.responseText
}

發送請求時post傳參

post傳參有三種方式: key=value&key=value&... FormData json字符串

//1. key=value&key=value&...
// application/x-www-form-urlencoded : 需要key=value這種結構的參數

var xhr = new XMLHttpRequest();

xhr.open('post', '/postData');


//將發送到服務器端的數據寫成一個字符串
var str = 'id=1&name=zs&age=20&...'

//發送請求之前一定要設置請求頭為 application/x-www-form-urlencoded
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');

xhr.send(str);

xhr.onload = function () {
    xhr.responseText
}
//2. 發送FormData類型的數據
//1) 直接獲取整個post表單的數據
var fm = document.querySelector('form');
var fd = new FormData(fm)


//2) 實例化一個空的FormData,再向里面append數據
var fd = new FormData();
fd.append('name', 'xiaoming');
fd.append('age', 20);
fd.append('img', this.files[0]);


//發送ajax請求時,如果發送到服務器端的數據為FormData時,不需要設置請求頭,需要將fd作為參數傳入send
var xhr = new XMLHttpRequest();

xhr.open('post', '/postData');

xhr.send(fd);

xhr.onload = function () {
    xhr.responseText
}
//3. 發送到服務器端的數據是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
}


免責聲明!

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



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