利用xhr请求get参数(感觉没用,jq的$.ajax就可以解决了)
//创建xhr对象
let xhr = new XMLHttpRequest()
//调用open函数,?后的字符串叫做:查询字符串
xhr.open('GET','http://liulongbin.top:3006/api/getbooks?id=1&bookname=西游记')
//调用send函数
xhr.send()
//监听事件
xhr.onreadystatechange = function () {
if(xhr.readyState===4&&xhr.status===200){
//获取服务器响应的数据
console.log(xhr.responseText)
}
}
JOSN 和 JS 转换
let josnstr = '{"a":"hello","b":"world"}'
console.log(JSON.parse(josnstr))
let str = {
a : 'wo',
b : 'ow'
}
console.log(JSON.stringify(str))
自己写ajax,感觉完全没意义,参照教程写的
function res (data) {
let arr = []
for (let k in data) {
let str = k+'='+data[k]
arr.push(str)
}
return arr.join('&')
}
function itheima (options) {
let xhr = new XMLHttpRequest()
//把外界传递过来的参数对象转为查询字符串
let qs = resolveData(options,data)
if(options.method.toUpperCase()==='GET'){
//发送get请求
xhr.open(options.method,options.url+'?'+qs)
xhr.send()
}else if(options.method.toUpperCase()==='post'){
//发送post请求
xhr.open(options.method,options.url)
xhr.setRequestHeader('Content-Type','application/x-www/form-urlencoded')
xhr.send(qs)
}
xhr.onreadystatechange = function () {
if (xhr.readyState===4&& xhr.status===200) {
let ress = JSON.parse(xhr.responseText)
options.succsee(ress)
}
}
}
let xhr = new XMLHttpRequest()
//设置时间
xhr.timeout = 3000
//指定超时的回调函数
//xhr.addEventListener('timeout',()=>console.log('请求超时'))
xhr.ontimeout = function () {
console.log('请求超时')
}
xhr.open('GET','http://www.liulongbin.top:3006/api/getbooks')
xhr.send()
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status===200){
console.log(xhr.response