get和post请求ajax区别:post请求需要在打开ajax对象之后,发送数据之前,设置请求头

—————————————————————————————————————————————————————

(1)get方式

//1.获取ajax对象
let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
//2.打开ajax对象
// xhr.open(请求方式,请求地址,布尔值) 
// 布尔值代表同步和异步 同步是false 异步是true 默认是异步
xhr.open('get', '/users/userNameGet?user=' + value);
//3.发送数据
xhr.send();
//4.设置ajax事件处理函数
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        //字符串转换为对象
        let data = JSON.parse(xhr.responseText)
        console.log('结果显示:', data);
    }
}

(2)post方式

//1.获取ajax对象
let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
//2.打开ajax对象
xhr.open('post', '/users/userNamePost');
//3.设置请求头
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
//4.发送数据:序列化
xhr.send('user=' + value);
//5.设置ajax事件处理函数
xhr.onreadystatechange = function() {
     if (xhr.readyState === 4 && xhr.status === 200) {
          let data = JSON.parse(xhr.responseText);
          console.log('结果显示:', data);
     }
}

更多推荐

ajax请求的四个步骤(原生)