原生ajax使用

原生ajax就是使用js对象,在js中就有个ajax的对象叫XMLHttpRequest。

代码中readyState:

 

 

使用方法见代码:

// 实例化XMLHttpResquest对象
var xhr = new XMLHttpresquest()
// 调用open方法选择请求类型和url地址
xhr.open('get or post','url地址?id=1&name=哈哈哈&.......')
// 发送send方法,发送Ajax请求
xhr.send()
// 监听事件,调用回调函数
xhr.onreaderstatuschange = function(){
    if(xhr.readyState === 4 && xhr.state === 200){
        // xhr.responseText就是服务器返回的数据
    }
}

 

 

// 1. 创建 xhr 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open()
xhr.open('POST', 'http://www.liulongbin.top:3006/api/addbook')
// 3. 设置 Content-Type 属性(固定写法)
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
// 4. 调用 send(),同时将数据以查询字符串的形式,提交给服务器
xhr.send('bookname=水浒传&author=施耐庵&publisher=天津图书出版社')
// 5. 监听 onreadystatechange 事件
xhr.onreadystatechange=function(){
    if(xhr.readyState===4&&xhr.status===200){
        console.log(xhr.responseText)
    }
}

 

 

 

 

 

 

posted @ 2022-08-15 17:35  漫步火星  阅读(90)  评论(0编辑  收藏  举报