(1)GET请求实现Ajax
//初始化,创建请求代理对象
var xhr = new XMLHttpRequest();
//open()方法表示建立一个与服务器特定端口的连接, GET 请求传递参数通常使用的是问号传参
// 这里可以在请求地址后面加上参数,从而传递数据到服务端
xhr.open('GET', './deleteServlet.java?id=1');
// 一般在 GET 请求时无需设置响应体,可以传 null 或者干脆不传
xhr.send(null);
//回调函数,处理响应结果
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
}
(2)POST请求实现Ajax
//创建初始化请求对象
var xhr = new XMLHttpRequest();
// open 方法的第一个参数的作用就是设置请求的 method
xhr.open('POST', './addServlet.java');
// 设置请求头中的 Content‐Type 为 application/x‐www‐form‐urlencoded
// 标识此次请求的请求体格式为 urlencoded 以便于服务端接收数据
xhr.setRequestHeader('Content‐Type', 'application/x‐www‐form‐urlencoded');
// 需要提交到服务端的数据可以通过 send 方法的参数传递
// 格式:key1=value1&key2=value2
xhr.send('key1=value1&key2=value2');
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
}