Ajax native data transmission, and a method of transmitting without

Js ajax request sent native

Step 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
}

When the transmission request parameter passing get

get parameters to be spliced ​​in the back of the url address to? Divided

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 transmission request parameter passing

post parameter passing in three ways: key = value & key = value & ... FormData json string

//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
}

Guess you like

Origin www.cnblogs.com/j-j-h/p/12056836.html