使用 Vue 的 axios 可以发送 HTTP 的 PUT 请求,用于修改一条数据。
axios.PUT(url, data).then((resp)=>{});
参数 | 描述 |
---|---|
PUT | 我们需要发送的是 Vue axios PUT 请求。 |
data | 发送 PUT 请求携带的数据。 |
url | 请求的服务器的 url。 |
then | 即请求完成后,服务器的回调。 |
首先,我们在 E:\workspace
目录,创建一个 db.json
文件,输入以下内容:
{
"JavaScript":[
{
"id": 1,
"category":"ES6",
"author": "HaiCoder1"
},
{
"id": 2,
"category":"Vue",
"author": "HaiCoder2"
}
],
"Server":[
{
"id": 1,
"category":"Docker",
"author": "HaiCoder3"
},
{
"id": 2,
"category":"Golang",
"author": "HaiCoder4"
},
{
"id": 3,
"category":"Python",
"author": "HaiCoder5"
}
]
}
接着,我们在该目录的地址栏,输入 cmd,打开 cmd 窗口,如下图:
输入 cmd 之后,直接回车,即可在此目录打开命令行,如下图所示:
我们在命令行,输入以下命令,启动 jsonserver:
json-server --watch db.json
更过有关 JsonServer 的使用,请参考前面的 JsonServer 教程。
使用 Vue-resource put 请求,修改一条数据
<!DOCTYPE html>
<html>
<head>
<title>Vue-axios put请求</title>
<script type="text/javascript" src="./lib/vue-2.6.10.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<input type="button" value="axios put 请求" @click='putInfo'>
<p>嗨客网(www.haicoder.net)</p>
</div>
</body>
<script type="text/javascript">
var vm = new Vue({
el : '#app',
data:{
msg: "嗨客网"
},
methods:{
putInfo() {
axios.put('http://localhost:3000/Server/1', {'category':'Js', 'author':'HaiCoder11'}).then((data)=>{
console.log(data);
});
}
}
});
</script>
</html>
我们点击按钮,向 JsonServer 发送请求,请求成功后,浏览器输出如下内容:
我们通过 Vue axios 发送了 HTTP 的 PUT 请求。我们再次,使用 GET 请求,获取 Server 模块的新数据,输入以下代码:
<!DOCTYPE html>
<html>
<head>
<title>Vue-axios get请求</title>
<script type="text/javascript" src="./lib/vue-2.6.10.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<input type="button" value="axios GET 请求" @click='getInfo'>
</div>
</body>
<script type="text/javascript">
var vm = new Vue({
el : '#app',
data:{
msg: "嗨客网"
},
methods:{
getInfo() {
axios.get('http://localhost:3000/Server').then((data)=>{
console.log(data);
});
}
}
});
</script>
</html>
我们点击按钮,向 JsonServer 发送请求,请求成功后,浏览器输出如下内容:
我们可以看到,Server 模块下面 id 为 1 的数据已经被修改了。
使用 Vue 的 axios 可以发送 HTTP 的 PUT 请求。Vue axios PUT 请求语法 为:
axios.PUT(url, data).then((resp)=>{});