一、问题描述:
首先在开发中,我想要设计一个弹出提出框可以让用户进行进一步确认操作后再进行接下来的请求。官方提供的一个提示框如下:
wx.showModal({ title: '提示', content: '这是一个模态弹窗', success (res) { if (res.confirm) { console.log('用户点击确定') } else if (res.cancel) { console.log('用户点击取消') } } })
这是一个模块弹出框,当用户点击确认后可以做后续操作。
二、问题案例:
接下来,是我做的案例。我想让用户确认积分兑换的操作。如果确认兑换那么后台进行操作。代码和演示图如下:
wx.showModal({ title: '提示', content: '确认兑换吗?', success: function (res) { if (res.confirm) {//这里是点击了确定以后 console.log('确定') wx.request({ url: this.data.api+'/wx/addExchangeRecord', data: record, method: 'POST', header: { 'content-Type': 'application/json' }, success:function(res){ console.log(res) if(res.data.code=='0'){ wx.showToast({ title: res.data.msg , icon: 'none', duration: 2500, }) }else{ wx.showToast({ title: res.data.msg, icon: 'error', duration: 2500 }) } } }) } else {//这里是点击了取消以后 console.log('用户点击取消') } } })
上面代码对应图上操作。让用户点击确认按钮后。进行:
if (res.confirm) {//这里是点击了确定以后 console.log('确定') wx.request({ url: this.data.api+'/wx/addExchangeRecord', data: record, method: 'POST', header: { 'content-Type': 'application/json' }, success:function(res){ console.log(res) if(res.data.code=='0'){ wx.showToast({ title: res.data.msg , icon: 'none', duration: 2500, }) }else{ wx.showToast({ title: res.data.msg, icon: 'error', duration: 2500 }) } } }) }
但是这里遇到一个问题。当点击确认按钮后,没有请求过去链接回调回来的响应。
三、问题分析:
首先,我们可以进行控制台调试,发现没有任何的network请求,说明我们访问的后台链接是错误的。
接着,这里使用了this.data.api+接口。但是这里的this,已经没有了作用域。
四、问题解决:
我们只需在点击确认按钮后,将this作用域赋值给一个临时变量,让临时变量去请求后台接口。修改如下。
var that = this url: that.data.api+'/wx/addExchangeRecord',
接下来我们再次请求下。效果如下:
成功解决问题!