ajax就是用到数据,请求服务器数据,然后返回数据。或者发送数据,然后数据传到服务器再返回数据。通过get可以请求数据,post发送数据 里面有三个参数() 第一个是请求的url地址,第二个是设置条件{id:2}例如找到id2的才会返回数据。第三个是function(i){返回的数据}回调函数。
还有 一个是ajax 都是通过$符号点出来,要接入jquery库
form表单提交会自动跳转页面preventDefault() 可以绑定表单,然后在表单上传数据的时候用这个函数可以阻止跳转,
模板引擎,方便操作,不用拼接字符串。
js原生的ajax操作,
// 1. 创建 XHR 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open 函数
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')
// 3. 调用 send 函数
xhr.send()
// 4. 监听 onreadystatechange 事件
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// 获取服务器响应的数据
console.log(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. 监听事件
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText)
}
}
var result = JSON.parse(xhr.responseText) 将json数据转化为数组
var xhr = new XMLHttpRequest()
// 设置 超时时间
xhr.timeout = 30
// 设置超时以后的处理函数
xhr.ontimeout = function () {
console.log('请求超时了!')
}