如何将自动填充搜索结果显示为链接

时间:2016-11-04 20:57:28

标签: jquery-ui laravel-5.2 jquery-ui-autocomplete

我已经在我的laravel项目"书店管理"中成功实施了自动完成搜索选项。再次从我的主页,如果我点击一本书的名称,那么它将显示特定的书。但是如何添加链接到我的搜索结果,这样如果我从结果中点击一本书,那么它将带我到包含书籍详细信息的页面。

我的index.blade.php

  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

    <script>
        $(function() {
            $( "#books" ).autocomplete({
                source: 'auto_complete'
            });


        });

    </script>

    <div class="ui-widget">
        <label for="books">Books: </label>
        <input id="books">
    </div>

控制器

public function search(){
        $search = Input::get('term');

        $books = Book::where('title','like','%'.$search.'%')->get();

        foreach ($books as $book) {
            $data[] = $book->title;
        }

//        return $books;
        return $data;
    }

路线

Route::get('auto_complete', 'BooksController@search');

1 个答案:

答案 0 :(得分:0)

CONTROLLER

public function search(){
        $search = Input::get('term');
        // return $search or dd($search) check if request get the value please
        $books = Book::where('title','like','%'.$search.'%')->get();
        // return $books or dd($books) check if request get the values please
        $results = array();
        foreach($books as $key => $v){
        $results[]=['id' => $v->id];
    }
    // return a json object
    return response()->json([
              'suggestions'=>$results]);
    }

JS

$(function() {
        $( "#books" ).autocomplete({
            source: 'auto_complete',
            onSelect: function (data) {
                location.href = "www.yourwebsite.com+data.suggestions.id" // this redirect for example book id:1 to www.yourwebsite.com/1
            // Or use jquery to redirect: window.location.replace("http://stackoverflow.com");
}
        });


    });

使用相同的路线,如果网络或控制台出现错误,请告诉我! 我认为你集成了jquery库和自动完成库js:)