微信小程序多商品评价评星提交
<form bindsubmit="submitComment">
<block wx:for="{{commentList}}" wx:key="{{item.g_id}}">
<view class="rating-top bgw">
<image src="{{url+item.thumb}}" class="proimg"></image>
<view class="rating-right">
<view class="">评分</view>
<view class="star-wrapper">
<block wx:for="{{starnum}}" wx:key="unique" wx:for-item="v">
<view class="star {{item.star>=v?'on':''}}" style="background-image:url({{star}})" bindtap="checkStar" data-num="{{v}}" data-id="{{item.g_id}}"></view>
</block>
</view>
</view>
</view>
<textarea auto-height class="rating-con bgw pd20" placeholder="请写下你对宝贝的感受吧,对其他人有很大帮助哦!" data-index="{{index}}" value="{{item.content}}" bindblur="saveContent"/>
</block>
<button class="submit" formType="submit">提交评价</button>
</form>
wxml页面结构如上。小程序的textarea组件的bindblur事件更新不及时,所以用form提交。
/**
* 星星选择
*/
checkStar: function (e) {
var commentList = this.data.commentList;
var id = parseInt(e.currentTarget.dataset.id);
var num = parseInt(e.currentTarget.dataset.num);
for (let i = 0, l = commentList.length; i < l; i++) {
if (commentList[i].g_id == id) {
commentList[i].star = num
}
}
this.setData({
'commentList': commentList
});
},
主要的难点在于双循环中要获取到上一个循环体当前索引,后来发现其实可以通过g_id而不是index来区分这是哪个商品的评价,这样一来就可以拿到每一个商品的星星评级。
/**
* 提交评价
*/
submitComment: function (e) {
var g_id = '';
var star = '';
var content = '';
var commentList = this.data.commentList;
for (var i = 0, len = commentList.length; i < len; i++) {
g_id += commentList[i].g_id + '>}';
star += commentList[i].star + '>}';
if (utils.judgeNull(commentList[i].content)) {
commentList[i].content = '系统默认好评'
}
// content.push(commentList[i].content);
content += commentList[i].content + '>}';
}
// console.log(content)
// console.log(g_id)
// console.log(star)
app.fetch1(API.addEvaluate,
{
uid: wx.getStorageSync('uid'),
user_id: wx.getStorageSync('user_id'),
g_id: g_id,
content: content,
star: star,
order_id: this.data.order_id
}, (err, data) => {
console.log(data)
if (data.code == ERR_OK) {
wx.showToast({
title: '提交评价成功!',
icon: 'success',
duration: 2000
})
setTimeout(function () {
wx.navigateBack({
})
}, 2000)
} else {
wx.showToast({
title: data.msg,
icon: 'loading',
duration: 2000
})
}
})
},
提交的时候有个坑,原本传给后端的数据应该是三个数组,但是它自动转成了字符串,后端同事查过后发现无解(或者暂时无解),于是选择直接拼接字符串传递,原本打算通过“,”区分,考虑到评价内容中可能出现的“,”最后决定以“}>”作为分隔。
|