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.

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

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题