简体   繁体   English

自动完成搜索在Laravel中不起作用

[英]Autocomplete Search not Working in Laravel

I have a search field with the same name and id inside my categories page and inside my products page.The autocomplete suggestions seems to work fine , however once I click on requested product inside the search field, it's stays on the same page and not redirecting me to the view.I want my view to show only products. 我的类别页面和产品页面中都有一个具有相同名称和ID的搜索字段。自动完成建议似乎可以正常工作,但是一旦我在搜索字段中单击所需的产品,它就会停留在同一页面上并且不会重定向我要查看。我希望我的视图仅显示产品。 This is my code so far: 到目前为止,这是我的代码:

After update 更新后

My routes: 我的路线:

<?php

Route::get('products/{id}', 'AutoCompleteController@show');
Route::get('autocomplete', array('as' => 'autocomplete', 'uses' => 'AutoCompleteController@show'));
Route::get('searchajax', array('as' => 'searchajax', 'uses' => 'AutoCompleteController@autoComplete')); 

My AutoCompleteController: 我的AutoCompleteController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\MainController;
use App\Product;

class AutoCompleteController extends MainController
{
    public function show(Product $product)
    {
        return view('content.products', ['product' => $product]);
    }

    public function autoComplete(Request $request)
    {
        $query = $request->get('term', '');

        $products = Product::where('title', 'LIKE', '%' . $query . '%')->get();

        $data = [];
        foreach ($products as $product) {
            $data[] = array('label' => $product->title, 'value' => $product->id);
        }
        if (count($data)) {
            return $data;
        } else {
            return ['value' => 'No Result Found', 'id' => ''];
        }
    }
}

My view in products.blade.php and categories.blade.php for my autocomplete search is the same: 对于自动完成搜索,我在products.blade.php和category.blade.php中的视图是相同的:

@extends('master')
@section('content')
    <link href="http://demo.expertphp.in/css/jquery.ui.autocomplete.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <div class="row">
        <form class="navbar-form text-center " form method="GET" action=" ">
            <input id="search_text" placeholder=" Search products" name="search_text" type="text" value=""
                   style="width: 400px; height: 35px; border-radius: 5px ; padding-left: 12px;"><br><br>
            <input class="btn btn-default " type="submit" value="  Search">
        </form>
    </div>

    <script>
        $(document).ready(function () {
            src = "{{ route('searchajax') }}";
            $("#search_text").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: src,
                        dataType: "json",
                        data: {
                            term: request.term
                        },
                        success: function (data) {
                            response(data);
                        }
                    });
                },
                minLength: 3,
                select: function (event, ui) {
                    window.location = '{{ url('shop/{category_url}')}}' + ui.item.id
                } // not sure if this is the correct way , please advise
            });
        });
    </script>
@endsection

If you seems the issue with JS conflict, try below code: 如果您发现JS冲突的问题,请尝试以下代码:

<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>

Added missing ui css too. 也添加了缺少的ui css。 Let me know the result. 让我知道结果。

There are a few problems: 有几个问题:

  • An autocomplete response should include label and value pairs, you are returning value and id . 自动完成响应应包括labelvalue对,您将返回valueid See the jQuery UI source docs . 请参阅jQuery UI源文档

  • Your Javascript is missing the select event handler, which specifies what happens when one of the suggestions is selected. 您的Javascript缺少select事件处理程序,该处理程序指定了选择建议之一时发生的情况。 So right now clicking one will just fill the clicked value in the input field. 因此,现在单击一个将仅在输入字段中填充单击的值。 See the jQueryUI autocomplete select docs . 请参阅jQueryUI自动完成选择文档

Maybe you want to be able to view product ID 1 when you browse to /products/1 . 浏览到/products/1时,也许您希望能够查看产品ID /products/1 First you need to set up a route for that: 首先,您需要为此设置一条路线:

Route::get('products/{id}', 'AutoCompleteController@index');

Then in your controller, first fix the autocomplete response to return the right format: 然后在您的控制器中,首先修复自动完成响应以返回正确的格式:

foreach ($products as $product) {
    $data[]=array('label'=>$product->title,'value'=>$product->id);
}

Next, still in the controller, update the method for showing your product (BTW this should probably be called show , index would usually be a list of products: 接下来,仍然在控制器中,更新显示产品的方法(顺便说一句,这可能应该称为showindex通常是产品列表:

use App\Product;

class AutoCompleteController extends MainController {

    // This assumes you have a Product model
    public function index(Product $product) {
        return view('content.products', ['product' => $product]);
    }

And your Javascript: 和您的Javascript:

$("#search_text").autocomplete({
    source: function (request, response) {
        $.ajax({
            url: src,
            dataType: "json",
            data: {
                term: request.term
            },
            success: function (data) {
                response(data);

            }
        });
    },
    minLength: 3,
    select: function( event, ui ) {
        // Your autoComplete response returns the ID in the 'value' field
        window.location = 'http://yoursite.com/products/' + ui.item.value
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM