微信小程序的AJAX初次体验

GET请求

//微信小程序用GET传送数据
//微信小程序通过 wx.request发送ajax请求
wx.request({
	url: app.globalData.pubSiteUrl + 'user-information/get-information', //url
	method: 'GET', //请求方式
	//设置请求的头部
	header: {
		'Content-Type': 'application/json',
	},
	//请求的参数
	//传进去的值;
	data: {
		activityId: options.id, //参数
	},
	//接口调用成功的回调函数
	//res返回的對象
	success: function(res) {
		if (res.data.code == 1) {
			_this.setData({
				phone: res.data.user.phone,
				password: res.data.user.password
			})
		}
	},
	//接口调用失败的回调函数
	fail: function() {
		app.consoleLog("请求数据失败");
	},
	//接口调用结束的回调函数(调用成功、失败都会执行)
	complete: function() {
		// complete 
	}
})

POST请求

//POST请求
//在小程序中,POST请求的Content-Type(必须)设置为:application/x-www-form-urlencoded
var _this = this;
wx.request({
	url: app.globalData.pubSiteUrl + 'statistics/detail-activity', //上线的话必须是https,没有appId的本地请求貌似不受影响 
	method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT 
	header: {
		'Content-Type': "application/x-www-form-urlencoded",
		// wx.getStorageSync("sessionId");本地缓存指定的key
		'Cookie': 'SESSION=' + wx.getStorageSync("sessionId")
	}, // 设置请求的 header
	//传入的数据
	data: {
		activityId: options.id,
	},
	//返回成功的回调函数
	success: function(res) {
		app.consoleLog("请求数据成功");
		_this.setData({ // 设置页面列表的内容
			activityDetail: res.data.activity
		});
		_this.getActivityDetials();
	},
	//返回失败的回调函数
	fail: function() {
		app.consoleLog("请求数据失败");
	},
	//Ajax结束返回的函数
	complete: function() {
		// complete 
	}
})

猜你喜欢

转载自blog.csdn.net/qq_39148344/article/details/88885423
今日推荐