js基础知识——ajax测试请求的方式和区别
一、ajax测试请求的方式
请求方式1
// 1.创建一个ajax对象
const xhr = new XMLHttpRequest()
// 2.配置ajax对象 xhr.open('请求方式','请求地址','一个布尔值')
xhr.open('get','http://localhost:8888/test/first',true)
// 3.发送请求
xhr.send()
// 4.接受响应
xhr.onload = function(){
// console.log('现在后端已经给我们返回了 我们想要的数据');
console.log(xhr.responseText);
}
请求方式2
//1.创建一个ajax对象
const xhr = new XMLHttpRequest
// 2.配置ajax对象
xhr.open('get','http://localhost:8888/test/second')
// 4.配置接受响应的函数
xhr.onload = function () {
const res = JSON.parse(xhr.responseText)
console.log(res)
}
// 3.发送请求
xhr.send()
请求方式3
//1.创建一个ajax对象
const xhr = new XMLHttpRequest
// 2.配置ajax对象
xhr.open('get','http://localhost:8888/test/third?name=hjx&age=20')
// 4.配置接受响应的函数
xhr.onload = function () {
const res = JSON.parse(xhr.responseText)
console.log(res)
}
// 3.发送请求
xhr.send()
请求方式4
/*
application/x-www-form-urlencoded 这是post 格式的传参是需要给 content-type 配置的属性值,这样传递表明需要的是 普通字符串
如果是 json 格式的字符串, 需要传递为 application/json
*/
// 1.创建一个ajax对象
const xhr = new XMLHttpRequest
// 2.配置ajax对象
xhr.open('post','http://localhost:8888/test/fourth')
// 4.配置接受响应的函数
xhr.onload = function () {
const res = JSON.parse(xhr.responseText)
console.log(res)
}
// 3.1 post 请求传参时需要配置 content-type(请求头内的属性)
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
// 3.2 发送请求
xhr.send('name:htd,age:18')
二、请求方式的区别
-
get 偏向于获取的语义(商品列表数据,用户详情,商品详情)
- delete 偏向于获取的语义(删除某一个内容)
-
post 偏向于修改的语义(修改用户名 修改密码)
- put 偏向于修改的语义 (修改库存,修改收藏数量)
-
目前 公司中常用的方式只有两个,get/post
- 请求方式不同,会导致传参的方式不同,除此之外对我们前端来说没有区别
get: 直接将需要传递参数拼接在路径后即可,注意使用? 间隔http://localhost:8888/test/first?key=valuepost: 也是需要传递字符串,只不过不放在 地址路径后,而是放在请求体内书写(其实就是 xhr.send() )- 在传参时需要配置一个请求头中的属性 content-type, content-type 赋值的时候,还要区分我们传递的是普通字符串,还是json格式的字符串
普通字符串:
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')json字符串:
xhr.setRequestHeader('content-type','application/json')