首页 > 热点 > 微信 > 正文

微信小程序搜索功能(附:小程序前端+PHP后端)

2024-07-22 01:19:01
字体:
来源:转载
供稿:网友

开发需求

微信小程序已经是非常火了,而且学习也比较容易,但是对于初学者来说还是一件比较伤脑筋的事,接下来给大家分享一下小程序搜索的思路。

流程

1、表单(输入框、提交按钮、提交的name值)
2、接收表单数据(js获取表单name=keyword的值)
3、通过wx.request向服务器后端发起请求查询数据库
4、返回JSON格式的数据给小程序,js解析渲染到小程序前端展示

界面

代码

index.wxml

<!-- 标题 --><view class="title">小程序搜索</view><!-- 搜索框view --><view class="search_con"><!-- 表单 --> <form bindsubmit="formSubmit"> <!-- 记得设置name值,这样JS才能接收name=keyword的值 -->  <input type="text" name="keyword" class="search_input" placeholder='你要找什么呢?'/>  <button formType="submit" class="search_btn">搜索</button>   </form></view><!-- 搜索结果展示 --><view wx:for="{{re}}" wx:key="re" class="search_result"><!-- 当提交空白表单的时候 --> <view class="empty">{{item.empty}}</view> <!-- 当有搜索结果的时候 --> <view class="resname">{{item.resname}}</view> <!-- 当查询不到结果的时候 --> <view class="noresult">{{item.noresult}}</view></view>

index.js

其中里面的

http://localhost/search.php?keyword=

是服务器后端接口,用于接收小程序传过去的关键词的,下面会有这个后端PHP文件。

const app = getApp()Page({ data: {}, //执行点击事件 formSubmit: function (e) {  //声明当天执行的  var that = this;  //获取表单所有name=keyword的值  var formData = e.detail.value.keyword;  //显示搜索中的提示  wx.showLoading({   title: '搜索中',   icon: 'loading'  })  //向搜索后端服务器发起请求  wx.request({   //URL   url: 'http://localhost/search.php?keyword=' + formData,   //发送的数据   data: formData,   //请求的数据时JSON格式   header: {    'Content-Type':'application/json'   },   //请求成功   success: function (res) {    //控制台打印(开发调试用)    console.log(res.data)    //把所有结果存进一个名为re的数组    that.setData({     re: res.data,    })    //搜索成功后,隐藏搜索中的提示    wx.hideLoading();   }  }) },})

index.wxss

/* 搜索样式 */.title{ text-align: center; font-size: 20px; font-weight: bold;}.search_con{ width: 80%; margin:20px auto;}.search_con .search_input{ border: 1px solid rgb(214, 211, 211); height: 45px; border-radius: 100px; font-size: 17px; padding-left: 15px;/*此处要用padding-left才可以把光标往右移动15像素,不可以用text-indent*/ color: #333;}.search_con .search_btn{ margin-top: 15px; width: 100%; height: 45px; background: #56b273; color: #fff; border-radius: 100px;}.search_result{ width: 80%; margin:10px auto;}.search_result .empty{ text-align: center; color: #f00; font-size: 15px;}.search_result .noresult{ text-align: center; color: #666; font-size: 15px;}.search_result .resname{ text-align: left; color: #333; font-size: 15px;}            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表