const xhr =new XMLHttpRequest()
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users', true)
xhr.send()
` xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
const users = JSON.parse(xhr.responseText)
const user = document.querySelector('.user')
console.log(user)
}
}`
发送一个登录的请求,需要向后台传递登录的数据
post 方法 https://cnodejs.org/api/v1/accesstoken
传递参数 accesstoken 值是String(用户的accessToken)
// post方法
const xhr = new XMLHttpRequest()
xhr.open('post', 'https://cnodejs.org/api/v1/accesstoken', true)
//传递数据一般 使用对象,然后转化成 json 再传递,比如这个 post 请求传递的参数,应该写成{accesstoken:值}对象的形式
//默认 原生的ajax 想要使用 json 数据传递给后台,是不可以的,需要设置请求的请求头使用setRequestHeader方法
xhr.setRequestHeader('Content-type', 'application/json')
xhr.send(JSON.stringify({ accesstoken: '261f3b58-da12-4164-80ea-b92ced0f6f47' }))
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(JSON.parse(xhr.responseText))
}
}
带参数的 get 请求
// get传参
const xhr = new XMLHttpRequest()
//当get 请求需要传递参数的时候可以直接将参数写在地址上,当成地址的查询部分
xhr.open('GET', 'https://cnodejs.org/api/v1/topics?tab=ask&page=1&limit=10')
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(JSON.parse(xhr.responseText))
}
}
如果想发多个请求,改个名 const xhr2=new XmlHttpRequest()
// 1. $.ajax({请求的配置})
$.ajax({
//地址
url: ('https://cnodejs.org/api/v1/accesstoken'),
//请求类型 默认 GET 须大写
type: 'POST',
//向后台传递的数据,直接写对象类型,无需写成json文件
//偶尔也可以用date传参
data: {
accesstoken: '261f3b58-da12-4164-80ea-b92ced0f6f47'
},
//请求成功的回调函数,请求成功后会自动执行,这个函数有个默认参数,这个参数就是请求返回结果,这个结果是对象类型(jq从json转过来
success(res) {
console.log(res)
},
//请求失败的回调函数,请求失败自动执行,err是错误信息
error(err) {
console.log(arr)
}
//发送给后台的数据类型设置,一般不用设置,我们传递数据使用对象即可
// contentType:
})
$.post(‘地址’,{参数},function(res){返回})
cdn :
// axios
axios.get('https://cnodejs.org/api/v1/topics?tab=ask&&limit=10&&page=1').then((res) => {
//res 其实是axios 封装配置后的返回值, 也就是将后台返回的数据进行了封装,res.data 才是真正后台返回的数据
console.log(res.data) //Object { success: true, data: (10) […] }
}).catch((err) => {
console.log(err)
})
axios.post('https://cnodejs.org/api/v1/accesstoken', { accesstoken: '261f3b58-da12-4164-80ea-b92ced0f6f47' }).then((res) => {
console.log(res.data) //Object { success: true, loginname: "YangluFover", avatar_url: "https://avatars.githubusercontent.com/u/91188060?v=4&s=120", id: "616539fcfe0c51cb11aee455" }
}).catch((err) => {
console.log(err)
})
//axios删除
axios.delete("http://localhost:3008/todos/" + id);
get
fetch('https://cnodejs.org/api/v1/topics?tab=ask&page=1&limit=10', { method: 'GET' }).then((el) => {
return el.json()
}).then((res) => {
console.log(res)
})
post
fetch('https://cnodejs.org/api/v1/accesstoken', { method: 'POST', body: JSON.stringify({ accesstoken: '261f3b58-da12-4164-80ea-b92ced0f6f47' }), headers: { 'content-type': 'application/json' } }).then((el) => {
return el.json()
}).then((res) => {
console.log(res)
})