Uniapp的Ajax具体实现(uni.request)

使用场景:

由于uniapp的官方文档对于Ajax的使用其实写的比较模糊,在两个月前首次使用uniapp开发的时候也是遇到了许多问题,下面也会贴出uniapp的Ajax代码


代码:

这里是一段模板

	方法名(){
    
    
		uni.request({
    
    
			header:{
    
     
				'Content-type':'application/x-www-form-urlencoded' //注意这里对应的是用Java搭建的服务器
			},
		    url: 接口路由地址,
		    method: 'POST',
		    dataType: 'json', //返回值类型
			data:{
    
    
				键:值, //传给后端的参数
			},
		    success: (res) => {
    
     //成功
		    	if(res.data.status == 100){
    
     //状态
		    	} else if(res.data.status == 200){
    
    
		    		uni.showToast({
    
     //弹出自动消失的提示框
		    			icon:'none',
		    			title:'数据不存在'
		    		});
		    	} else if(res.data.status == xxx) {
    
    
					uni.showToast({
    
    
						icon:'loading',
						title:'网络请求失败'
					})
				}
		    },
		    fail() {
    
     //失败
		    	uni.showToast({
    
    
					icon:'loading',
					title:'网络请求失败'
				})
		    },
		});
	},

注意事项:

对于服务端(后端)环境搭建的语言不同,请求头header里的内容也要相应的做变换,我这里给出的是Java做后端的请求头。当然,如果你的后台是使用node.js搭建的,请求头需要换成node.js的请求头


猜你喜欢

转载自blog.csdn.net/qq_45596525/article/details/112387215