前端调用Api接口常用的请求方式
一、使用ajax请求主要使用到的参数:(url、type、data、dataType、success、error等,其他可根据需求)$.ajax({//请求的地址 url:"http://localhost:8080/json/test.json", //请求方式,可用“get”或者“post”,默认为“get” type:"post", //设置请求超时时间(毫秒)。此设置将覆盖$.aj
·
一、使用ajax请求
主要使用到的参数:(url、type、data、dataType、success、error等,其他可根据需求)
$.ajax({
//请求的地址
url:"http://localhost:8080/json/test.json",
//请求方式,可用“get”或者“post”,默认为“get”
type:"post",
//设置请求超时时间(毫秒)。此设置将覆盖$.ajaxSetup()方法的全局设置。
timeout:10000
//Boolean类型的参数,默认为true,即所有请求均为异步请求。为false时为同步请求
async:true
//要求为Object或String类型的参数,发送到服务器端的数据。
data:{}
//服务器返回的数据类型。常用的数据类型有:text表示纯文本 xml表示xml数据 json表示json对象
dataType: "json"
//要求为Function类型的参数,发送请求前可以修改
beforeSend:function(option) {
//在这里写发送请求前想做的事
}
//请求成功后响应的回调函数
success:function(data){
console.log(data)
//在这里写请求成功后想做的事
}
//请求失败时响应的函数
error:function(err){
console.log(err)
//在这里写请求失败后做的事
}
//当发送信息至服务器时内容编码类型默认为"application/x-www-form-urlencoded"。
//其他格式还有application/json,multipart/form-data(多用于表单),text/xml
contentType: "application/json"
})
二、使用axios请求
这是基于vue中使用的,基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 Node.js 中使用。
this.$axios({
method:"post",//请求方式post或get 默认get
url:"http://localhost:8080/json/test.json",//请求的地址
//请求头参数
headers:{
token:"e770d10d38bde4027b6783a8102ea56020c1d23f"
}
//请求参数
params:{
user:"xgb",
password:"123456"
}
//请求体
data:data,
timeout:10000 //超时时间
}).then((res) =>{
console.log(res)
//在这里写请求成功后想做的事
}).catch(function (err) {
console.log(err)
//在这里写请求失败后想做的事
})
更多推荐
所有评论(0)