我想在我的應用程序創建一個搜索模塊,但是從我的數據庫的響應是以下格式並且我得到一個錯誤從服務器獲取響應的Json格式錯誤。如何使其以所需格式響應?
ERROR SyntaxError: Unexpected token s in JSON at position 0
sa[{"id":"4","worklocation":"Hyderabad","firstname":"Sanjay","lastname":"Tutuki","gender":"Male","aadharno":"0","panno":"2147483647","employeetype":"asdasd","dateofbirth":"2017-07-12","city":"Mumbai"}]
我如何度過,即使沒有它我搜索與術語作出迴應?或者如何在沒有錯誤的情況下獲取組件中的值。
這是我的代碼:
service.ts:
search(terms: Observable<string>) {
return terms.debounceTime(400)
.distinctUntilChanged()
.switchMap(term => this.searchEntries(term));
}
searchEntries(term) {
const baseUrl="http://localhost/Angular/search.php?search="
return this.http
.get(baseUrl + term)
.map(res => res.json());
}
組件:
export class EmployeeDirectory {
data : Data[];
searchTerm$ = new Subject<string>();
constructor(private dataservice : DataService){
this.dataservice.search(this.searchTerm$)
.subscribe(data => {
this.data = data.data;
console.log(data);
});
}
search(searchTerm$){
this.dataservice.search(this.searchTerm$)
.subscribe(data => {
this.data = data.data;
console.log(data);
});
}
}
模板:
<div class="col-md-6 col-sm-12 col-xs-12 ">
<form method="GET" name="form" autocomplete="off">
<div class="col-lg-9">
<div class="input-group">
<input type="text" class="form-control" (keyup)="searchTerm$.next($event.target.value)" placeholder="Search for...">
<span class="input-group-btn">
<button class="btn btn-secondary" type="button" (click)="search(this.searchTerm$)" ><i class="glyphicon glyphicon-search"></i></button>
</span>
</div>
</div>
</form>
</div>
<div *ngIf="data">
<table *ngFor="let employee of data">
<tr><td>First Name: </td><td>{{employee.firstname}}</td></tr>
</table>
PHP文件:
<?php
header("Allow-Access-Header-Origin: *");
$servername ="localhost";
$username ="root";
$password="sandeepchetikam";
$dbase = "mydb";
$conn = mysqli_connect($servername,$username,$password,$dbase);
if(!$conn){
echo "Error" .mysqli_error($conn);
}
$name =$_GET['search'];
print_r($name);
$sql = "SELECT * FROM newdb WHERE firstname LIKE '%{$name}%' ";
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_assoc($result))
{
$rows[] = $row;
}
echo json_encode($rows);
?>
而且該函數僅對第一個搜索鍵作出響應,並且它不適用於其他搜索項。誰能幫我這個?
你沒有刪除'的print_r($名)'當你正在測試這個權利? – apokryfos
是的,這是問題。感謝大家 。有人可以幫助我嗎?我如何使搜索按鈕作爲搜索而不是關鍵?如何發送searchTerm $的按鈕? – Prakash
我很確定你可以谷歌。 – apokryfos