1.$.ajax的get请求
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
dataType: "json",
type: "get",
params: {},
//发送之前做的事情
beforeSend: function(xhr) {
console.log("befor send")
},
//发送成功后做的事情
success: function(data) {
console.log(data)
},
error: function() {
console.log("失败")
}
})
2.$.ajax的post请求
$.ajax({
url: "http://localhost:3000/users",
dataType: "json",
type: "post",
data: {
"name": "www",
"age": 23,
"class": 1
},
beforeSend: function(xhr) {
console.log("befor send")
},
success: function(data) {
console.log(data)
},
error: function() {
console.log("失败")
}
})
二、$.ajax的其他方法
1.$.get()
// 语法:$(selector).get(url,data,success(response,status,xhr),dataType)
$.get("https://jsonplaceholder.typicode.com/posts",{"id":1},function(data){
console.log(data)
},"json")
2.$.post
//语法:jQuery.post(url,data,success(data, textStatus, jqXHR),dataType)
$.post("http://localhost:3000/users", {
"name": "www",
"age": 23,
"class": 1
},function(data){
console.log(data)
},"json")
三、Aioxs
//Axios API
/**
* 可以通过向 axios() 传递相关配置来创建请求
* axios(config) config 为对象格式的配置选项
* axios(url,config) config 可选
*//**
* axios(config) config 为对象格式的配置选项
* 常用配置项
* url 用于请求的服务器url
* method 创建请求时使用的方法
* baseURL 传递相对 URL 前缀,将自动加在 url 前面
* headers 即将被发送的自定义请求头
* params 即将与请求一起发送的 URL 参数
* data 作为请求主体被发送的数据
* timeout 指定请求超时的毫秒数
* responseType 表示服务器响应的数据类型,默认"json"
*/
//get方法
axios({
url:"/posts",
method:"get",
baseURL:"https://jsonplaceholder.typicode.com",
headers:{
"Content-Type":"application/json"
},
params:{
id:1
}
})
.then(function(response){
console.log(response.data)
})
//post方法
axios({
url:"/users",
method:"post",
baseURL:" http://localhost:3000/",
headers:{
"Content-Type":"application/json"
},
data:{
"name": "youss",
"age": 19,
"class": 1
}
})
.then(function(response){
console.log(response.data)
})
//config可选
//axios(url,config) config 可选
axios("https://jsonplaceholder.typicode.com/posts",{
params:{
id:1
}
})
.then(function(response){
console.log(response.data)
})
1.axios的拦截器
可以通过在请求之前拦截设置baseURL参数,在多个相同的请求中省去代码
//使用拦截器对请求进行拦截处理
axios.interceptors.request.use(function (config) {
config.params = {
id:2
}
config.baseURL = "http://localhost:3000/"
return config;
})
//对响应进行拦截
axios.interceptors.response.use(function (response) {
return response.data;
})
axios("/users")
.then(function(response){
console.log(response)
})
axios的快速请求方法
//get方法
axios.get("http://localhost:3000/users",{
params:{
id:1
}
})
.then(function (res) {
console.log(res.data)
})
// post 方法
axios.post("http://localhost:3000/posts",{
data:{
"title": "sss-server",
"author": "sss"
}
})
.then(function (res) {
console.log(res.data)
})
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)