我一直在研究一个简单的Laravel CRUD应用程序。我想为它实现搜索功能,所以我使用了ajax调用。但我的代码无效。
web.php
Route::post('/search',[
'as' => 'searchbox',
'uses' => 'HomeController@postSearch'
]);
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 :(得分:0)
在{!! csrf_field() !!}
元素中添加<form>..</form>
。
所有post/put/patch
请求都应该发送csrf_token或请求将失败。
答案 1 :(得分:0)
检查行
$items = Item::where('title', 'like', '%' . 'title1' . '%')->paginate(10);`,
我认为它应该是
$items = Item::where('title', 'like', '%' . $request->input('body') . '%')->paginate(10);
现在您只需搜索字符串title1