您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)如何在微信小程序中實(shí)現(xiàn)一個(gè)搜索功能,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
index.wxml
<!--index.wxml--> <form bindsubmit="formSubmit"> <!--提交按鈕 --> <input type="text" name="id" placeholder='輸入關(guān)鍵詞' style='border:1px solid #ccc;height:30px;'/> <button formType="submit" class="btn">搜索</button> </form> <view>搜索結(jié)果</view> <view wx:for="{{re}}" wx:key="re"> <view style='color:#f00;'>{{item.result}}</view> <view style='color:green;'>{{item.title}}</view> </view>
*跟前端差不多,form表單要加一個(gè)bindsubmit="formSubmit"
接著就是index.js
//index.js //獲取應(yīng)用實(shí)例 const app = getApp() Page({ /** * 頁面的初始數(shù)據(jù) */ data: { result:'', state:'' }, formSubmit: function (e) { var that = this; var formData = e.detail.value.id; //獲取表單所有name=id的值 wx.request({ url: 'http://localhost/2018-5-24/search.php?id=' + formData, data: formData, header: { 'Content-Type': 'application/json' }, success: function (res) { console.log(res.data) that.setData({ re: res.data, }) wx.showToast({ title: '已提交', icon: 'success', duration: 2000 }) } }) }, })
url: 'http://localhost/2018-5-24/search.php?id=' + formData,
這個(gè)很容易理解
var that = this; var formData = e.detail.value.id;
先把表單name=id的值獲得,然后賦給formData這個(gè)變量
然后,在url進(jìn)行拼接,用+號(hào)拼接這個(gè)變量即可...
然后,提交到接口,后端進(jìn)行處理即可,后端處理后返回json格式的數(shù)據(jù),然后通過
that.setData({ re: res.data, })
進(jìn)行打印在控制臺(tái),你也可以渲染在index.wxml
為了方便大家研究,我把后端的php源碼也貼出來。
search.php
<?php header("Content-type:text/json;charset=utf8"); //定義參數(shù) $id = $_GET["id"]; //表單驗(yàn)證 if(empty($id)){ echo "[{\"result\":\"表單為空...\"}]"; }else{ //連接數(shù)據(jù)庫 $con = mysql_connect("數(shù)據(jù)庫鏈接","賬號(hào)","密碼"); //設(shè)置數(shù)據(jù)庫字符集 mysql_query("SET NAMES UTF8"); //查詢數(shù)據(jù)庫 mysql_select_db("數(shù)據(jù)庫名", $con); $result = mysql_query("SELECT * FROM test WHERE id like '%$id%'"); $results = array(); while($row = mysql_fetch_assoc($result)) { $results[] = $row; // 將數(shù)組轉(zhuǎn)成json格式 echo json_encode($results); } //關(guān)閉數(shù)據(jù)庫連接 mysql_close($con); } ?>
*數(shù)據(jù)庫表名為test,里面一共有兩個(gè)字段,一個(gè)是id,一個(gè)是title
所以index.wxml里面有兩個(gè)值
<view wx:for="{{re}}" wx:key="re"> <view style='color:#f00;'>{{item.result}}</view> <view style='color:green;'>{{item.title}}</view> </view>
上述就是小編為大家分享的如何在微信小程序中實(shí)現(xiàn)一個(gè)搜索功能了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。