从PHP脚本搜索栏和结果

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (103)

您好我已经创建了一个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>
提问于
用户回答回答于

好吧,我将假设你的authservice提供程序工作正常,我会告诉你这个没有框架,我将不会使用jwt或oauth或一些身份验证系统进行身份验证,但会直接回答你的问题:首先你可能想要触发一个http请求当用户按下回车键或按键时,按键进入。在ion-searchbar中删除(ionInput)方法并使用角度中的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();
         }

        })

    }


  }

让我解释一下,我们绑定到离子搜索栏的搜索内容将被检查,如果它是空的,如果是,我们什么也不做或没有显示任何内容然后我们调用我们的http服务提供商发送一个http请求传递search_content binded到元素和是的,我忘了我们使用了一个我们称为加载器的LoadingController你可以创建一个单独的服务提供者来处理它并将提供者导入你的文件,然后使用loadcontroller使代码更清晰,现在接下来是返回响应值http服务,并将其值分配给名为response_data的全局变量。现在这是重要的,在映射后不要直接在你的视图中使用它,因为一旦你的搜索结果没有返回任何东西它会抛出一个错误,这似乎是离子3中的一个错误我想。

<?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我使用limit 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>

那应该做的。

扫码关注云+社区

领取腾讯云代金券

玩转腾讯云 有奖征文活动