VUE-ajax

server/2024/9/22 13:46:59/

ajax_0">VUE-ajax

vue-resource的介绍

vue-resource是Vue高度集成的第三方包。

官网链接:

  • 文档(http相关):https://github.com/pagekit/vue-resource/blob/master/docs/http.md

vue-resource 依赖于 Vue。所以,我们要按照先后顺序,导入vue.js和vue-resource.js文件。

解释

vue.js文件向Windows对象暴露了Vue这个关键词;vue-resource.js向Vue身上挂载了this.$http这个属性。于是,我们可以直接写this.$http.get或者this.$http.post或者this.$http.jsonp来调用。

vue-resource 发送Ajax请求

见的数据请求类型包括:get、post、jsonp。下面我们分别讲一讲。

get请求

this.$http.get(url).then(function (result) { // 当发起get请求之后,通过 .then 来设置成功的回调函数console.log(result.body); // response.body就是服务器返回的成功的数据var result = result.body;},function (err) {//err是异常数据});

获取到的response.body就是要获取的数据,但直接打印出来是 object,所以要记得转成string。

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title><script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script><script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.1"></script><style>#test {width: 800px;margin: 20px auto;}#tb {width: 800px;border-collapse: collapse;margin: 20px auto;}#tb th {background-color: #0094ff;color: white;font-size: 16px;padding: 5px;text-align: center;border: 1px solid black;}#tb td {padding: 5px;text-align: center;border: 1px solid black;}</style></head><body><div id="test"><input type="text" v-model="country"> <input type="text" v-model="gold_num"><input type="text" v-model="score"><button>addDate</button><table id="tb"><tr><th>name</th><th>gold_num</th><th>score</th><th>operator</th></tr><tr v-for="item in list"><td>{{item.countryid}}</td><td>{{item.gold}}</td><td>{{item.rank}}</td><td><a href="javascript:void(0)">edit</a></td></tr></table></div><script>new Vue({el: "#test",data:{list: [],country: "",gold_num: 0,score: 0,},// Vue对象实例创建成功以后就会自动调用这个方法created:function(){this.getList()},methods: {getList: function(){// 请求服务器的api获取到奥运会排行榜this.$http.get("https://api.oioweb.cn/api/search/getOlyMedals").then(function (res) {// 1、处理服务器异常信息提示if (res.body.code != 200) {alert(res.body.message)return;}// 2、处理正常的数据逻辑this.list = res.body.result.medalsList; //直接将数据放到list数组当中,页面就会自动显console.log(this.list);})}}})</script></body></html>

上方代码中,我们用到了生命周期函数created,意思是:程序一加载,就马上在created这个函数里执行getlist()方法。

Post请求

格式举例

// 方法:$http.post(url, 传给服务器的请求体中的数据, {emulateJSON:true})
// 通过 post 方法的第三个参数{ emulateJSON: true } ,来设置 提交的内容类型 为 普通表单数据格式
this.$http.post(url, { name: '奔驰' }, { emulateJSON: true }).then(function (response) {alert(response.body.message);},function (error) {});
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title><script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script><script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.1"></script><style>#test {width: 800px;margin: 20px auto;}#tb {width: 800px;border-collapse: collapse;margin: 20px auto;}#tb th {background-color: #0094ff;color: white;font-size: 16px;padding: 5px;text-align: center;border: 1px solid black;}#tb td {padding: 5px;text-align: center;border: 1px solid black;}</style></head><body><div id="test"><input type="text" v-model="id"> <input type="text" v-model="userId"><input type="text" v-model="title"><button @click="addDate">addDate</button><table id="tb"><tr><th>id</th><th>userId</th><th>title</th><th>operator</th></tr><tr v-for="item in list"><td>{{item.id}}</td><td>{{item.userId}}</td><td>{{item.title}}</td><td><a href="javascript:void(0)">edit</a></td></tr></table></div><script>new Vue({el: "#test",data:{list: [],id: 0,userId: 0,title: "",},created:function(){this.getList()},methods: {getList: function(){this.$http.get("http://jsonplaceholder.typicode.com/posts").then(function (res) {if (res.status != 200) {alert("failed")return;}this.list = res.body;})},addDate: function(){var url = "http://jsonplaceholder.typicode.com/posts";var postData = {id: this.id,userId: this.userId,title: this.title};var options = { emulateJSON: true };this.$http.post(url, postData, options).then(function (res) {console.log(res)if (res.status != 201) {alert(" add failed")return;}this.id=0;this.userId=0;this.title=""this.getList();})}}})</script></body></html>

delete

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>Document</title><style>#app {width: 800px;margin: 20px auto;}#tb {width: 800px;border-collapse: collapse;margin: 20px auto;}#tb th {background-color: #0094ff;color: white;font-size: 16px;padding: 5px;text-align: center;border: 1px solid black;}#tb td {padding: 5px;text-align: center;border: 1px solid black;}</style><script src="vue.js"></script><script src="vue-resource121.js"></script>
</head><body><div id="app"><input type="text" v-model="pname"><button @click="adddata">添加数据</button><table id="tb"><tr><th>编号</th><th>名称</th><th>创建时间</th><th>操作</th></tr><tr v-for="item in list"><td>{{item.id}}</td><td>{{item.name}}</td><td>{{item.ctime}}</td><td><!-- 具体要删除哪个item,不能写死。所以要根据id来删 --><a href="javascript:void(0)" @click="deldata(item.id)">删除</a></td></tr></table></div>
</body>
<script>new Vue({el: '#app',data: {pname: '', //这个 pname 是我在输入框里添加的数据。我们要把这个传给服务器list: []},// Vue对象实例创建成功以后就会自动调用这个方法created: function () {this.getlist();},methods: {//ajax请求:添加数据adddata: function () {// 1、获取用户填写的文本框的值只需要通过this.pname即可// 2、调用ajax的post方法将数据上传到服务器var url = 'http://vueapi.ittun.com/api/addproduct';var postData = { name: this.pname };  //【重要】键`name`是json中约定好的字段。我们把这个字段传给服务器var options = { emulateJSON: true };this.$http.post(url, postData, options).then(function (response) {if (response.body.status != 0) {alert(response.body.message);return;}this.pname = '';// 3、直接将列表数据重新加载一次,即可刷新页面上的数据this.getlist();});},//ajax请求:获取数据getlist: function () {this.$http.get('http://vueapi.ittun.com/api/getprodlist').then(function (response) {// 1、处理服务器异常信息提示if (response.body.status != 0) {alert(response.body.message);return;}// 2、处理正常的数据逻辑this.list = response.body.message;console.log(this.list);});},// ajax请求:删除数据deldata: function (id) {this.$http.get('http://vueapi.ittun.com/api/delproduct/' + id).then(function (response) {if (response.body.status != 0) {alert(response.body.message);return;}// 刷新列表this.getlist();});}}});
</script></html>

jsonp介绍

// 利用vue-resource中的jsonp方法实现跨域请求数据,这里要注意的是:
// url后面不需要跟callback=fn这个参数了,jsonp方法会自动加上
this.$http.jsonp('http://vuecms.ittun.com/api/getlunbo?id=1').then(function (response) {console.log(JSON.stringify(response.body));}, function (err) {//err是异常数据});
原理

由于浏览器的安全性限制,默认不允许Ajax发起跨域(协议不同、域名不同、端口号不同)的请求。浏览器认为这种访问不安全。

JSONP的实现原理:通过动态创建script标签的形式,用script标签的src属性,代表api接口的url,因为script标签不存在跨域限制,这种数据获取方式,称作JSONP(注意:根据JSONP的实现原理,知晓,JSONP只支持Get请求)。

具体实现过程:

  • 先在客户端定义一个回调方法,预定义对数据的操作
  • 再把这个回调方法的名称,通过URL传参的形式,提交到服务器的api接口;
  • 服务器api接口组织好要发送给客户端的数据,再拿着客户端传递过来的回调方法名称,拼接出一个调用这个方法的字符串,发送给客户端去解析执行;
  • 客户端拿到服务器返回的字符串之后,当作Script脚本去解析执行,这样就能够拿到JSONP的数据了
axios

除了 vue-resource 之外,还可以使用 axios 的第三方包实现实现数据的请求。

通过Vue全局配置api接口的url地址

api接口的url地址包括:绝对路径+相对路径。

我们在做Ajax请求的时候,所填写的url建议填相对路径,然后把绝对路径放在全局的位置。

Vue就提供了这个功能。举例如下:

  <script>// 如果我们通过全局配置了,请求的数据接口 根域名,则 ,在每次单独发起 http 请求的时候,请求的 url 路径,应该以相对路径开头,前面不能带 /  ,否则 不会启用根路径做拼接;Vue.http.options.root = 'http://smyhvae/';// 全局启用 emulateJSON 选项Vue.http.options.emulateJSON = true;var vm = new Vue({el: '#app',data: {name: '',list: [ // 存放所有品牌列表的数组]},created() { // 当 vm 实例 的 data 和 methods 初始化完毕后,vm实例会自动执行created 这个生命周期函数this.getAllList()},methods: {getAllList() { // 获取所有的品牌列表// 分析:// 1. 由于已经导入了 Vue-resource这个包,所以 ,可以直接通过  this.$http 来发起数据请求// 2. 根据接口API文档,知道,获取列表的时候,应该发起一个 get 请求// 3. this.$http.get('url').then(function(result){})// 4. 当通过 then 指定回调函数之后,在回调函数中,可以拿到数据服务器返回的 result// 5. 先判断 result.status 是否等于0,如果等于0,就成功了,可以 把 result.message 赋值给 this.list ; 如果不等于0,可以弹框提醒,获取数据失败!this.$http.get('api/getprodlist').then(result => {// 注意: 通过 $http 获取到的数据,都在 result.body 中放着var result = result.bodyif (result.status === 0) {// 成功了this.list = result.message} else {// 失败了alert('获取数据失败!')}})}}});</script>

如上方代码所示,第一步是在全局的位置写绝对路径

    Vue.http.options.root = 'http://smyhvae/';

第二步是在Ajax请求的url中写相对路径:(注意,前面不要带/

this.$http.get('api/getprodlist')

http://www.ppmy.cn/server/11407.html

相关文章

Ai终端程序推荐waveterm

有没有人根据Ai的风口&#xff0c;做智能终端呢&#xff1f;答案是真有&#xff0c;真有专为无缝工作流程而构建的开源 AI 原生终端。它是去年推出的一个产品&#xff0c;专为程序员和开发者设计&#xff0c;比较创新的一点是所有的工作可以在终端完成&#xff0c;开源和可扩展…

JavaSE——程序逻辑控制

1. 顺序结构 顺序结构 比较简单&#xff0c;按照代码书写的顺序一行一行执行。 例如&#xff1a; public static void main(String[] args) {System.out.println(111);System.out.println(222);System.out.println(333);} 运行结果如下&#xff1a; 如果调整代码的书写顺序 , …

OpenHarmony图片处理——XmlGraphicsBatik

简介 XmlGraphicsBatik项目用于处理可缩放矢量图形&#xff08;SVG&#xff09;格式的图像&#xff0c;例如显示、生成、解析或者操作图像。 支持SVG图像的显示&#xff0c;可显示静态及动态SVG图像&#xff1b; 支持快捷生成SVG图像文件&#xff1b; 支持操作SVG图像进行颜…

python使用tkinter和ttkbootstrap制作UI界面(二)

这次讲解UI界面常用的主键&#xff0c;延续上文的框架进行编写&#xff0c;原界面如下&#xff1a; Combobox组件应用&#xff08;下拉框&#xff09; """Combobox组件"""global comvalue_operatorcomvalue_operator tk.StringVar()value_ope…

Ubuntu或Debian系统的漏洞修复:apt安装包管理工具

在阿里云主机管理后台->安全云中心&#xff0c;会看到系统最新的公布漏洞。 对于系统软件漏洞&#xff0c;我们还是要早做修复&#xff0c;防患于未然。 但安全云中心的功能大部分需要付费&#xff0c;包括一键修复&#xff0c;自己修复软件漏洞怎么操作呢&#xff1f; 其…

AI日报:最强大模型Llama 3发布;Midjourney推社交新功能Room;超强AI视频自动剪辑工具Captions;手机上可以玩大模型了

新鲜AI产品点击了解&#xff1a;https://top.aibase.com/ 1、最强大模型Llama3 正式发布 已达GPT4 级别 Llama3是Meta公司最新发布的开源模型&#xff0c;拥有80亿和700亿参数规模&#xff0c;预计7月正式发布。该模型具备多模态能力&#xff0c;集成了新的计算机编码功能&am…

电机控制专题(一)——最大转矩电流比MTPA控制

文章目录 电机控制专题(一)——最大转矩电流比MTPA控制前言理论推导仿真验证轻载1Nm重载30Nm 总结 电机控制专题(一)——最大转矩电流比MTPA控制 前言 MTPA全称为Max Torque Per Ampere&#xff0c;从字面意思就可以知道MTPA算法的目的是一个寻优最值问题&#xff0c;可以从以…

牛客NC195 二叉树的直径【simple DFS C++ / Java /Go/ PHP】

题目 题目链接&#xff1a; https://www.nowcoder.com/practice/15f977cedc5a4ffa8f03a3433d18650d 思路 最长路径有两种情况&#xff1a; 1.最长条路径经过根节点&#xff0c;那么只需要找出根节点的左右两棵子树的最大深度然后相加即可。 2.最长路径没有经过根节点&#xf…