request.uvue 1.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
<template>
	<view>
		<page-head :title="title"></page-head>
		<view class="uni-padding-wrap uni-common-mt">
			<view class="uni-hello-text">
				请点击按钮向服务器发起请求
			</view>
			<view class="uni-textarea uni-common-mt">
				<textarea :value="res"></textarea>
			</view>
			<view class="uni-btn-v uni-common-mt">
12
				<button type="primary" @click="sendRequest">发起请求(Callback)</button>
13 14 15 16 17
			</view>
		</view>
	</view>
</template>
<script>
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
18
	import RequestTask from 'uts.sdk.modules.DCloudUniNetwork.RequestTask';
19 20 21 22 23
	const duration = 2000
	export default {
		data() {
			return {
				title: 'request',
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
24 25 26
				res: '',
				task: null as RequestTask | null,
				pageVisible: false
27 28
			}
		},
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
29 30 31 32 33 34 35 36
		onLoad() {
			this.pageVisible = true;
		},
		onUnload() {
			this.pageVisible = false;
			uni.hideLoading();
			this.task?.abort();
		},
37 38
		methods: {
			sendRequest() {
39 40 41
				uni.showLoading({
					title:"请求中..."
				})
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
				this.task = uni.request({
					url: "https://unidemo.dcloud.net.cn/ajax/echo/text?name=uni-app",
					dataType: "json",
					responseType: "json",
					method: "POST",
					data: {
						platform: "ios",
					},
					header: {
						"Content-Type": "application/json",
					},
					timeout: 6000,
					sslVerify: false,
					withCredentials: false,
					firstIpv4: false,
					success(res) {
						if (this.pageVisible) {
							console.log('request success', res)
							uni.showToast({
								title: '请求成功',
								icon: 'success',
								mask: true,
								duration: duration
							});
							this.res = '请求结果 : ' + JSON.stringify(res);
						}
					},
					fail(err) {
						if (this.pageVisible) {
							console.log('request fail', err);
							uni.showModal({
								content: err.errMsg,
								showCancel: false
							});
						}
					},
					complete() {
79
						uni.hideLoading()
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
80 81
					},
				});
82 83 84
			}
		}
	}
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
85
</script>