drlnwji79147769 2018-04-26 14:27
浏览 98
已采纳

如何使用Laravel Controller进行jQuery自动完成(=实时搜索)

This is (part of) my view, generated by Laravel Forms:

<form method="POST" action="http://laravelapp/search" accept-charset="UTF-8">
    <input name="_token" type="hidden" value="g3RA...">
    <input type="text" placeholder="Search" id="terms">
</form>

<script>
$( function() {
    var testdata = [ "ActionScript", "AppleScript", "JavaScript" ];
    $( "#terms" ).autocomplete({
        minLength: 1,
        source: '{{ URL::route('index.search') }}'
        //source: testdata
    });
});
</script>

These is the route for index.search:

Route::post('/search', 'IndexController@search')->name('index.search');

This is my IndexController:

public function search(Request $request)
{
   return Response('Hello World');
}

For the sake of simplicity, I replaced the actual search algorithm with a static response Hello World. However, the autocomplete works fine if I uncomment the //source: testdata line in the javascript code. When I use the route to the IndexController, nothing happens.

When I press enter (=submit the form), a new page is loaded with Hello World, but there's no dynamic search result.

As you can see, I inserted the CSRF token and the search()method returns a valid response. However, it is not triggered by the javascript. My questions, thus, are:

  • What's wrong with my code?
  • Should the route be GET or POST?
  • Should there be a form around the input field? Usual jQuery demo examples don't have it, but it's probably needed for the CSRF protection.

Any help is greatly appreciated!

  • 写回答

1条回答 默认 最新

  • dousong2967 2018-04-26 18:25
    关注

    The autocomplete expects its source to be an array of data. By default the way to respond this back to the client is in the json format. You should try changing your endpoint to not only return an array, but encode that array into the json format so autocomplete will know how to handle it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?