微信小程序搜索功能!附:小程序前端+PHP後端

開發需求

微信小程序已是很是火了,並且學習也比較容易,可是對於初學者來講仍是一件比較傷腦筋的事,接下來給你們分享一下小程序搜索的思路。php

流程

一、表單(輸入框、提交按鈕、提交的name值)
二、接收表單數據(js獲取表單name=keyword的值)
三、經過wx.request向服務器後端發起請求查詢數據庫
四、返回JSON格式的數據給小程序,js解析渲染到小程序前端展現前端

界面

clipboard.png

代碼

index.wxmlmysql

<!-- 標題 -->
<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?k...
是服務器後端接口,用於接收小程序傳過去的關鍵詞的,下面會有這個後端PHP文件。sql

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;
}

服務端

search.phpjson

<?php
header('Content-Type:application/json');

//獲取表單數據
$keyword1 = $_GET["keyword"];

//過濾表單空格
$keyword2 = trim($keyword1);

//當表單提交空白數據時
if(empty($keyword2)){
    
    //構建數組
    $arr = array(
            "empty" => "表單不能爲空"
        );

    //把數組轉換爲json
    $data = json_encode($arr);
    echo "[$data]";

}else{

//過濾表單特殊字符
$replace = array('!','@','#','$','%','^','&','*','(',')','_','-','+','=','{','}','[',']',';',':','"','<','>','?','/','|');
$keyword3 = str_replace($replace, '', $keyword2);

// 鏈接數據庫
$con = mysql_connect("數據庫地址","數據庫帳號","數據庫密碼");
if (!$con){die('Could not connect: ' . mysql_error());}

mysql_select_db("數據庫名", $con);
mysql_query("SET NAMES UTF8");

//查詢數據庫
$result = mysql_query("SELECT * FROM 表名 WHERE 須要查詢的字段 like '%$keyword3%' ORDER BY ID DESC");
$results = array();
//查詢數據庫是否存在這條記錄
$exist = mysql_num_rows($result);
if ($exist) {
    //遍歷輸出
    while ($row = mysql_fetch_assoc($result)){
        $results[] = $row;
        }

    //輸出JSON
    echo json_encode($results);

    //當查詢無結果的時候
    }else{

        //構建數組
        $arr = array(
            "noresult" => "暫無結果"
        );

        //把數組轉換爲json
        $data = json_encode($arr);
        echo "[$data]";
}

//斷開數據庫鏈接
mysql_close($con);
}
?>

服務端也是很是簡單的,你們本身把服務端寫好一點,畢竟安全和效率是很重要的。小程序

演示

圖片描述

做者:TANKING
網站:http://likeyunba.com
微信:face6009
(學習交流能夠加我)後端

相關文章
相關標籤/搜索