let xhr = new XMLHttpRequest()
xhr.open(‘get’, ‘example.php?query=4&em=0’)
xhr.send()
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
if(xhr.status === 200){
console.log(xhr.responseText);
}
}
}
发送post请求的过程几乎和get请求一样,唯一不一样的是数据的传递。大家都知道post请求的数据是放在请求体中的,因此我们需要调用xhr对象上的 setRequestHeader()
方法来模仿表单提交时的内容类型
该方法传入的参数比较固定,代码如下
xhr.setRequestHeader(‘Content-Type’, ‘application/x-www-form-urlencoded’)
然后我们上面也说过,send()
方法接收的一个参数是请求主体发送的数据,所以我们的post请求要发送的数据就要作为该方法的参数,代码如下:
xhr.send(‘query=4&em=0’)
那我们来看一次完整的post请求是怎么样的吧,代码如下:
let xhr = new XMLHttpRequest()
xhr.open(‘post’, ‘example.php’)
xhr.setRequestHeader(‘Content-Type’, ‘application/x-www-form-urlencoded’)
xhr.send(‘query=4&em=0’)
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
if(xhr.status === 200){
console.log(xhr.responseText);
}
}
}
=================================================================
文章开头提到,JQuery早已对Ajax请求进行了成熟的封装,所以我们可以借鉴它,甚至尽可能地去模仿它进行封装,在这之前,我们得先了解JQuery中Ajax的使用
这里我找来了几段使用JQuery发送Ajax请求的代码,如下所示:
- 发送get请求
$.get(‘example.php’, {query: 4, em: 0}, function(data, status, xhr) {
console.log(`
返回的数据为${data}
返回的状态为${status}
返回xhr对象为${xhr}
`)
}, ‘json’)
这段代码发送了一个 get
请求,携带的参数有 query
值为 4
、em
值为 0
,规定返回的数据类型为 json
,同时设定了一个回调函数用于接收请求返回的数据、状态和xhr对象
- 发送post请求
$.post(‘example.php’, {query: 4, em: 0}, function(data, status, xhr) {
co