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.

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

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题