一、用原生ajax的get方式请求数据
// 1.创建 XMLHttpRequest实例对象
let xhr = new XMLHttpRequest();
// 2.准备请求
xhr.open("get", "http://localhost:3000/get_test?get_name=xiao&get_addr=he", true);
// 3.执行请求
xhr.send();
// 4.监听状态变化,当请求完成并且响应已就绪再操作响应数据
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == "200") {
console.log(xhr.responseText);
}
}
注:
1.open方法的第一个参数是表示请求方式 即 get或post
第二个参数是请求的url地址
第三个参数是否异步 true为异步 false为同步
2.send方法参数表示post请求携带的数据,格式为"key1=val1&key2=val2",get请求不用写
3.readyState 表示 XMLHttpRequest的状态信息 ,有五个状态
4 表示请求已完成
0 表示请求未初始化
1 服务器连接已建立
2 请求已接收
3 请求处理中
4.当readyState的状态发生变化时,就会触发onreadystatechange函数
5.responseText表示服务器响应非XML的响应数据
附控制台打印:
二、用原生ajax的post方式请求数据
let xhr=new XMLHttpRequest();
xhr.open("post","http://localhost:3000/post_test",true);
//把请求头的媒体类型设置为url编码,这一步一定要设置,不然后台会接收不到前端传来的post数据
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send("post_name=xiao&post_addr=h");
xhr.onreadystatechange=function(){
if( xhr.readyState==4&&xhr.status=="200"){
console.log(xhr.responseText);
}
}
附控制台打印: