从PHP脚本搜索栏和结果

时间:2018-04-13 20:08:59

标签: ionic-framework ionic3

您好我已经创建了一个SearchPage但我不知道如何使用php脚本返回搜索结果。我已经建立了一个authservice提供程序来连接数据库,并且只要我调用它来返回会话用户的数据就可以正常工作。我希望用户在搜索栏上输入字母,结果显示在

<ion-content padding>
<ion-card *ngFor="let item of dataSet; let msgIndex = index">

authservice.ts

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

let apiUrl = "http://localhost/PHP-Slim-Restful1/api/";

@Injectable()
export class AuthService {

constructor(public http: Http) {
console.log('Hello AuthService Provider');
 }

 postData(credentials, type){

  return new Promise((resolve, reject) =>{
let headers = new Headers();
 this.http.post(apiUrl+type, JSON.stringify(credentials), {headers:   headers}).
 subscribe(res =>{
  resolve(res.json());
  }, (err) =>{
  reject(err);
 });

});

 }

 }

SearchPage.ts

  @Component({ selector: "page-search", templateUrl: "search.html" })
 export class SearchPage {
  public userDetails: any;
  public resposeData: any;
 public dataSet: any;
 public noRecords: boolean;
  userPostData = {
  uid: "",
  token: "",
  username: "",
  bio: "",
  profile_pic: "",
  message: "",
  msg_id: "",
   title: "",
   description: "",
  media_pic: "",
   created: "",
  uid_fk: ""
};

constructor(
 public common: Common,
 public navCtrl: NavController,
 public app: App,
 public menu: MenuController,
 public authService: AuthService,
 platform: Platform,
 statusBar: StatusBar,
 splashScreen: SplashScreen
  ) {
     const data = JSON.parse(localStorage.getItem("userData"));
  this.userDetails = data.userData;
  this.userPostData.uid = this.userDetails.uid;
  this.userPostData.token = this.userDetails.token;
  this.userPostData.username = this.userDetails.username;
  this.userPostData.msg_id = this.userDetails.msg_id;
  this.userPostData.message = this.userDetails.message;
  this.userPostData.title = this.userDetails.title;
  this.userPostData.description = this.userDetails.description;
  this.userPostData.media_pic = this.userDetails.media_pic;
  this.userPostData.created = this.userDetails.created;
  this.userPostData.profile_pic = this.userDetails.profile_pic;
  this.userPostData.bio = this.userDetails.bio;
  this.noRecords = false
  this.SearchResults();
 }


  SearchResults() {
  this.authService.postData(this.userPostData, "userGroupSearch").then(

   result => {
       this.resposeData = result;
       if (this.resposeData.userGroupSearch) {
           this.dataSet = this.resposeData.userGroupSearch;
           console.log(this.dataSet);

       } else {
           console.log("No access");
       }
   },
   err => {
       //Connection failed message
   }
  );
 }

我在这里调用PHP函数userGroupSearch是函数的名称

  this.authService.postData(this.userPostData, "userGroupSearch").then(

JSON在这里返回

  this.dataSet = this.resposeData.userGroupSearch;

SearchPage.html

   <ion-header>
   <ion-navbar>
  <button ion-button menuToggle>
  <ion-icon name="menu"></ion-icon>
   </button>
   <ion-searchbar [(ngModel)]="myInput"
           [showCancelButton]="shouldShowCancel"
           (ionInput)="onInput($event)"
           (ionCancel)="onCancel($event)"
           placeholder="Search for Media, Artists, Flows...">
    </ion-searchbar>
    </ion-navbar>

    <ion-content padding>
    <ion-card *ngFor="let item of dataSet; let msgIndex = index"></ion-card>
    </ion-content>

1 个答案:

答案 0 :(得分:0)

好吧,我将假设您的authservice提供程序运行良好,我将使用php no framework向您显示此信息,并且我将不使用jwt或oauth或某些身份验证系统进行身份验证,但直接回答您的问题: 首先,您可能希望在用户按下Enter键或向上键时触发一个http请求,但随着Enter键松开。 在ion-searchbar中,删除(ionInput)方法并使用如下所示的angular的key.enter事件:

<ion-searchbar placeholder="search by name of articles" (keyup.enter)="search()" [(ngModel)]="search_content"></ion-searchbar> 

现在搜索功能将使用您的authservice povider发送一个http get请求,我的代码为我的HTTPprovider,这是代码:

search(){

    if(this.search_content==""){

    }else{
      let loader = this.loader.create({
        content: "please wait..."
      });
      loader.present();
      this.HttpProvider.getData("search-post.php?search="+this.search_content).then((res)=>{
        this.response_data = res;
          if(this.response_data==null){            
          loader.dismiss();
         }else{
           this.result = this.response_data;
           loader.dismiss();
         }

        })

    }


  }

让我解释一下,我们绑定到ion-searchbar的搜索内容 将检查是否为空,如果是,则不执行任何操作或不显示任何内容,然后调用我们的http服务提供商,该服务提供商发送通过绑定到元素的search_content传递的http请求,以免我忘了我们使用了一个称为Loader的LoadingController可以创建单独的服务提供者来处理该问题,并将提供者导入您的文件,然后使用使代码更整洁的loadingcontroller,现在,下一步是返回http服务的响应值,并将其值分配给一个名为response_data的全局变量。现在,这很重要,因为它已被映射,请勿在您的视图中直接使用它,因为一旦您的搜索结果未返回任何内容,它将抛出错误,这似乎是ionic 3中的错误。完成检查后,检查response_data对象是否为null,否则将其分配给另一个名为result的值,最后关闭我们的加载控制器....... 对于我们的php文件:

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods:PUT, GET, POST, DELETE, OPTIONS");
require_once "config/config.php";
require_once "config/error.php";
$conn = new config();
$get_var = htmlspecialchars($_GET["search"]);
$space_checker = preg_match("/\s/",$get_var);
$data = array();
if($get_var==""){

 } else {
   if($space_checker==0){
    $sql = "SELECT * FROM post_content where header LIKE '%$get_var%' LIMIT 3";
$result = $conn->query($sql);
        $rowcount = $conn->rowcount($result);
        if($rowcount == 0){

        }else{
            foreach ($result as $key => $value) {
                $data[] = $value;
            }

         print json_encode($data);
        }


   }elseif ($space_checker > 0) {

$value_explode = explode(" ",$get_var);

 foreach ($value_explode as $key => $values) {
     $sql = "SELECT * FROM post_content where header LIKE '%$get_var%' OR '%$values%' ";
 }
     $sql.="LIMIT 3";

$result = $conn->query($sql);
$rowcounts = $conn->rowcount($result);
if($rowcounts == 0){
}else{

    foreach ($result as $key => $valuese) {
        $data[] = $valuese;
    }

    print json_encode($data);

}

   } 

}


?>

对于php文件,首先我们使用正则表达式检查单词之间的空格数,然后检查发送的get变量是否等于空字符串 我们什么也不显示,然后检查空格数是否等于零(如果它包含一些搜索内容)并且等于零(基本上它有一些内容,但搜索之间没有空格)。我们在PHP中使用like关键字搜索之后,将其保存在数组中并用json_encode进行编码,我使用限制3来返回3个内容,当然,只有分页,我相信您也知道。现在如果存在空间,我们会爆炸它并获取每个单词并搜索在搜索中输入的全文和单个单词,然后返回json_encoded的3个内容。

最后,在我们的视图中,我们使用* ngFor将其显示:

<ion-list style="margin-top:50px;">
          <ion-item *ngFor="let items of result"   >
            <ion-thumbnail item-left>
              <img src="{{ image }}/{{ items.file_name }}">
            </ion-thumbnail>
            <h4 style="font-weight:bolder;">{{ items.header }}</h4>
            <p> <b><span style="font-size:10px;">  <ion-icon name="eye"></ion-icon> {{ items.clicks }} views</span> 
             &nbsp;&nbsp; <span style="font-size:10px;"> <ion-icon name="clipboard"></ion-icon> {{ items.month }}/{{ items.year }}</span> 
    </b></p>
          </ion-item>
        </ion-list>

那应该做。