小程序实现搜索框功能向后台发送请求
我主要实现了小程序的功能,就没有后台代码了,直接看代码把。
.wxml
<input style="border:1px solid #ccc;float:left;" bindinput='changeSearch' placeholder="请输入名称搜索" type="text" name="name"></input>
<view bindtap="returns" class="inse">取消</view>
<!--取消返回上级 -->
<!-- 然后进行判断 -->
<!-- 查询出来自己自定义输出 -->
<view wx:if="{{inputValue != ''}}">
</view>
<!-- 没查询出来输出这个 -->
<view wx:if="{{inputValue == '' || inputValue == null}}">
</view>
.js
let api = require('../../utils/api.js');
let http = require('../../utils/httpUtil.js');
Page({
data: {
},
//点击取消
returns: function (e) {
wx.navigateBack({
delta: 1
})
},
//搜索框
changeSearch: function (e) {
this.setData({
inputValue: e.detail.value//监听键盘的输出
})
console.log(this.data.inputValue)
let param = {
"name": this.data.inputValue//把键盘的值传到后台去
}
let that = this
let token = wx.getStorageSync('token');
http.request(api.price, param, 'get', '查询', token, null).then(function (res) {
that.setData({
search: res.data//获取后台查询出来的值
})
console.log('返回数据:', res.data)
})
}
})
然后就是上面那些封装代码了
api.js
const baseUrl = '请求地址';
module.exports = {
price: baseUrl +'文件地址'
}
httpUtil.js
function request(url, data, method, title, token, contentType) {
wx.showNavigationBarLoading();
return new Promise((resove, reject) => {
wx.request({
url: url,
method: method.toUpperCase(),
data: data,
header: {
'content-type': contentType ? contentType:'application/json',
'Authorization': token
},
success: function (res) {
wx.hideNavigationBarLoading();
console.log(title + '返回的数据=======', res);
if(res.code == 301){
resove(null);
}else{
resove(res.data);
}
},
fail: function (msg) {
console.log(title + '请求失败=======', msg)
wx.hideNavigationBarLoading();
reject('fail')
}
})
})
}
module.exports = {
request: request,
}
分装的代码我前面几篇文章有的,有什么问题欢迎评论留言,我会及时回复你的。