当前位置: 首页 > article >正文

Vue.js Ajax(vue-resource)

Vue 要实现异步加载需要使用到 vue-resource 库。

Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。

<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>

Get 请求

以下是一个简单的 Get 请求实例,请求地址是一个简单的 txt 文本:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例</title>
<script src="https://cdn.staticfile.net/vue/2.4.2/vue.min.js"></script>
<script src="https://cdn.staticfile.net/vue-resource/1.5.1/vue-resource.min.js"></script>
</head>
<body>
<div id="box">
	<input type="button" @click="get()" value="点我异步获取数据(Get)">
</div>
<script type = "text/javascript">
window.onload = function(){
var vm = new Vue({
    el:'#box',
    data:{
        msg:'Hello World!',
    },
    methods:{
        get:function(){
            //发送get请求
            this.$http.get('/try/ajax/ajax_info.txt').then(function(res){
                document.write(res.body);    
            },function(){
                console.log('请求失败处理');
            });
        }
    }
});
}
</script>
</body>
</html>

如果需要传递数据,可以使用 this.$http.get('get.php',{params : jsonData}) 格式,第二个参数 jsonData 就是传到后端的数据。

this.$http.get('get.php',{params : {a:1,b:2}}).then(function(res){
    document.write(res.body);    
},function(res){
    console.log(res.status);
});

post 请求

post 发送数据到后端,需要第三个参数 {emulateJSON:true}。

emulateJSON 的作用: 如果Web服务器无法处理编码为 application/json 的请求,你可以启用 emulateJSON 选项。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例</title>
<script src="https://cdn.staticfile.net/vue/2.4.2/vue.min.js"></script>
<script src="https://cdn.staticfile.net/vue-resource/1.5.1/vue-resource.min.js"></script>
</head>
<body>
<div id="box">
	<input type="button" @click="post()" value="点我----智能安全。无处不在。">
</div>
<script type = "text/javascript">
window.onload = function(){
	var vm = new Vue({
	    el:'#box',
	    data:{
	        msg:'Hello World!',
	    },
	    methods:{
	        post:function(){
	            //发送 post 请求
	            this.$http.post('/try/ajax/demo_test_post.php',{name:"BlackBerry",url:"https://www.blackberry.com/cn/zh"},{emulateJSON:true}).then(function(res){
                    document.write(res.body);    
                },function(res){
                    console.log(res.status);
                });
	        }
	    }
	});
}
</script>
</body>
</html>

demo_test_post.php 代码如下:

<?php
$name = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '';
$city = isset($_POST['url']) ? htmlspecialchars($_POST['url']) : '';
echo '网站名: ' . $name;
echo "\n";
echo 'URL 地址: ' .$city;
?>

语法 & API

你可以使用全局对象方式 Vue.http 或者在一个 Vue 实例的内部使用 this.$http来发起 HTTP 请求。

// 基于全局Vue对象使用http
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

// 在一个Vue实例内使用$http
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

vue-resource 提供了 7 种请求 API(REST 风格):

get(url, [options])
head(url, [options])
delete(url, [options])
jsonp(url, [options])
post(url, [body], [options])
put(url, [body], [options])
patch(url, [body], [options])

除了 jsonp 以外,另外 6 种的 API 名称是标准的 HTTP 方法。

options 参数说明:

参数类型描述
urlstring请求的目标URL
bodyObject, FormData, string作为请求体发送的数据
headersObject作为请求头部发送的头部对象
paramsObject作为URL参数的参数对象
methodstringHTTP方法 (例如GET,POST,...)
timeoutnumber请求超时(单位:毫秒) (0表示永不超时)
beforefunction(request)在请求发送之前修改请求的回调函数
progressfunction(event)用于处理上传进度的回调函数 ProgressEvent
credentialsboolean是否需要出示用于跨站点请求的凭据
emulateHTTPboolean是否需要通过设置X-HTTP-Method-Override头部并且以传统POST方式发送PUT,PATCH和DELETE请求。
emulateJSONboolean设置请求体的类型为application/x-www-form-urlencoded

 通过如下属性和方法处理一个请求获取到的响应对象:

属性类型描述
urlstring响应的 URL 源
bodyObject, Blob, string响应体数据
headersHeader请求头部对象
okboolean当 HTTP 响应码为 200 到 299 之间的数值时该值为 true
statusnumberHTTP 响应码
statusTextstringHTTP 响应状态
方法类型描述
text()约定值以字符串方式返回响应体
json()约定值以格式化后的 json 对象方式返回响应体
blob()约定值以二进制 Blob 对象方式返回响应体

http://www.kler.cn/a/487610.html

相关文章:

  • XML通过HTTP POST 请求发送到指定的 API 地址,进行数据回传
  • 【算法】一阶低通滤波
  • 单向循环链表的约瑟夫环问题
  • Vue 3 和 Electron 来构建一个桌面端应用
  • STM32 : 奈奎斯特-香农采样定理
  • JavaScript语言的学习路线
  • ChatGPT入门之文本情绪识别:先了解LSTM如何处理文字序列
  • c#集成itext7导出pdf,包含表格
  • 基于SpringBoot的中国陕西民俗网的设计与实现(源码+SQL脚本+LW+部署讲解等)
  • 阅读笔记——《A survey of protocol fuzzing》
  • RabbitMQ解决消息积压的方法
  • SpringCloud Feign 全局Fallback的另一种实现方式(SpringBoot3.4+)
  • iPad编程新体验:如何用IDE Code App实现远程在线开发告别电脑束缚
  • 大纲笔记幕布的替换
  • 基于伪分布式模式和完全分布式模式部署ZooKeeper集群
  • C# 值类型和引用类型详解
  • Delphi+SQL Server实现的(GUI)户籍管理系统
  • 数据结构-线性表的概念与C语言实现
  • VSCode 插件
  • 使用强化学习训练神经网络玩俄罗斯方块