10.24 2018-11-20 19:26 采纳率: 0%
浏览 48

在Symfony中使用AJAX

I am trying to use "typeahead" function with Symfony. But my AJax code seem not to be working. Can you guys point me out to the fault?I searched in the internet many times and all most all the questions asked regarding this has not being answered well. Please if someone can arrange these to work in symfony 2.8, it will be a great help to lot of people.Thank you

My Twig code

<script>
$(document).ready(function(){
 
 $('#country').typeahead({
  source: function(query, result)
  {
   $.ajax({
    url:"{{path('fetch')}}",
    method:"POST",
    data:{query:query},
    dataType:"json",
    success:function(data)
    {
     result($.map(data, function(item){
      return item;
     }));
    }
   })
  }
 });
 
});
</script>
<input type="text" name="country" id="country" class="form-control input-lg" autocomplete="off" placeholder="Type Country Name" />

My controller

/**
 * @Route("/fetch", name="fetch")
 */
public function preAllAction(Request $request)
{

    //fetch.php
    $connect = mysqli_connect("localhost", "root", "root", "galleit");
    $request = mysqli_real_escape_string($connect, $_POST["query"]);
    $query = "SELECT * FROM products WHERE name LIKE '%".$request."%'";

    $result = mysqli_query($connect, $query);

    $data = array();

    if(mysqli_num_rows($result) > 0)
    {
        while($row = mysqli_fetch_assoc($result))
        {
            $data[] = $row["name"];
        }
        echo json_encode($data);
    }

}
</div>
  • 写回答

1条回答 默认 最新

  • weixin_33693070 2018-11-20 21:02
    关注

    Are you sure that your Symfony controller returns a response (any type it is)?
    You should replace echo json_encode($data) by return new JsonResponse($data)


    Make sure the JsonResponse class has been loaded by your controller.

    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作