// 1.创建ajax对象
var xhr = new XMLHttpRequest();
// 2.告诉Ajax对象要向哪发送请求,以什么方式发送请求
// 1)请求方式 2)请求地址
xhr.open('get', 'http://localhost:3000/first');
// 3.发送请求
xhr.send();
// 4.获取服务器端响应到客户端的数据
xhr.onload = function (){
console.log(xhr.responseText)
}
get参数传递
// 创建ajax对象
var xhr = new XMLHttpRequest();
// 获取用户在文本框中输入的值
var nameValue = username.value;
var ageValue = age.value;
// 拼接请求参数
var params = 'username='+ nameValue +'&age=' + ageValue;
// 配置ajax对象
xhr.open('get', 'http://localhost:3000/get?'+params);
// 发送请求
xhr.send();
// 获取服务器端响应的数据
xhr.onload = function () {
console.log(xhr.responseText)
}
post参数传递
// 创建ajax对象
var xhr = new XMLHttpRequest();
// 获取用户在文本框中输入的值
var nameValue = username.value;
var ageValue = age.value;
// 拼接请求参数
var params = 'username='+ nameValue +'&age=' + ageValue;
// 配置ajax对象
xhr.open('post', 'http://localhost:3000/post');
// 设置请求参数格式的类型(post请求必须要设置)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// 发送请求
xhr.send(params);
// 获取服务器端响应的数据
xhr.onload = function () {
console.log(xhr.responseText)
}