2016-11-15 52 views
0

我一直在研究一個簡單的Laravel CRUD應用程序。我想實現搜索功能,所以我用ajax調用它。但我的代碼不起作用。laravel中使用ajax進行搜索的問題

web.php

Route::post('/search',[ 
    'as' => 'searchbox', 
    'uses' => '[email protected]' 
    ]); 

HomeController.php

public function postSearch(Request $request) 
    { 
# code... 
    $items = Item::where('title', 'like', '%' . 'title1' . '%')->paginate(10); 
    // return response()->json(['msg-body'=>$request['body']],200); 
    return view('welcome')->with(['items'=>$items]); 

} 

welcome.blade.php

@extends('layouts.master') 
@section('title') 
Welcome 
@endsection 
@section('content') 
<div class="row" > 
    <div class="col-lg-12"> 
     <div class="col-lg-3"> 
      <h4>Crud</h4> 
     </div> 
     <div class="col-lg-4 col-lg-offset-3"> 
      <form method="POST" action=> 
      <input class="search" type ="text" name ="search" id="search" placeholder="search" > 

      </form> 
     </div> 
     <div class="pull-right"> 

      <a href="{{route('create')}}"class="btn btn-primary" >Create new item</a> 
     </div> 
    </div> 
    <div class="col-lg-12"> 
     <table class="table"> 
      <thead> 
       <tr> 
       <th>Id</th> 
       <th>Title</th> 
       <th>Description</th> 
       <th style="width: width="280px";">Action</th> 
       </tr> 
      </thead> 
      <tbody> 
       @foreach($items as $item) 
       <tr ng-model="search_query"> 
       <td>{{$item->id}}</td> 
       <td>{{$item->title}}</td> 
       <td>{{$item->description}}</td> 
       <td><a href="{{route('showdetails',['id'=>$item->id])}}" class="btn btn-info">show</a><a href="{{route('editdetails',['id'=>$item->id])}}" class="btn btn-primary">Edit</a><a href="{{route('delete',['id'=>$item->id])}}" class="btn btn-danger">Delete</a></td> 
       </tr> 
       @endforeach 
      </tbody> 
     </table> 
    </div> 
</div> 
<script type="text/javascript"> 
var token = '{{Session::token()}}'; 
var url = '{{route('searchbox')}}'; 
</script> 
{{ $items->render()}} 
@endsection 

style.js

$('.search').on('change',function(){ 
$.ajax({ 
     method: 'post', 
     url:url, 
     data:{body: $("#search").val(),_token:token} 
    }).done(function(msg){ 
     console.log($("#search").val()); 
    }) 
    }); 

任何人都可以給我建議......

+0

什麼叫 「代碼不工作」 的意思。請解釋你遇到的問題或任何錯誤 – jaysingkar

+0

'style.js'中'url'變量的值是什麼?我想你還沒有啓動url變量。 – jaysingkar

+0

當我搜索了一些標題它不工作。沒有更改列表 – user3860618

回答

0

添加{!! csrf_field() !!},您<form>..</form>元素中。 所有post/put/patch請求應發送csrf_token或請求將失敗。

+0

在blade.php文件末尾的腳本標記中添加了 – user3860618

0

查線

$items = Item::where('title', 'like', '%' . 'title1' . '%')->paginate(10);`, 

,我認爲它應該是

$items = Item::where('title', 'like', '%' . $request->input('body') . '%')->paginate(10); 

現在你只要搜索字符串title1

+0

我試過了,因爲我只是爲了靜態而實現它。 – user3860618

+0

那麼你在網絡響應或控制檯中得到了什麼? –

+0

在我的網絡控制檯iam獲取搜索輸出作爲required.but mty頁面也不重定向到本地主機:8000 /搜索.so我沒有得到任何過濾的數據 – user3860618