谁还没个明天 2018-01-31 22:44 采纳率: 50%
浏览 91

Ajax搜索表单Django

Trying to create a search form .Currently using ajax autocomplete function for this purpose.

  <div  class="ui-widget">
   <label for="search">Search for friends: </label>
   <input id="search">
 </div>



   $(function() {
  $("#search").autocomplete({
    source: "/accounts/ajax/search/",
    minLength: 2,
    select: function( event, ui )
  });
});

Below is my view that processes my ajax request.

 def get_ajax_search(request):
    query = request.GET.get('term', '')
    print(query)
    if request.is_ajax():
        qs1 = BasicUser.objects.filter(Q(first_name__icontains=query)) 
        results = []
        for user in qs1:
            basic_user_json = {}
            basic_user_json['id'] = user.pk
            basic_user_json['label'] = user.first_name+" "+  user.last_name
            basic_user_json['value'] = user.first_name+" "+  user.last_name
            results.append(basic_user_json)
    else:
        data = 'fail'
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)

Appreciate your help with a couple of questions:

  1. How can I redirect to a different page when selecting results.
  2. How can I display a user profile picture next to every search result
  • 写回答

1条回答 默认 最新

  • 程序go 2018-01-31 22:56
    关注
    1. How can I redirect to a different page when selecting results. Try something like below example:

    Here is a plunker https://plnkr.co/edit/MieqYB6K7inzPVBiinDZ?p=preview

    $("#search").autocomplete({
        source: "/accounts/ajax/search/",
        minLength: 2,
        select: function( event, ui ) {
    
            window.open('http://example.com/'+ui.item.value, '_blank')
        }
      });
    
    1. How can I display a user profile picture next to every search result Most importantly

    You can follow

    jquery autocomplete display custom result

    1. is there a better way of retrieving data from the database and sending it to the ajax function, assuming it's going to be a high load website. Any ideas or insights would be appreciated.

    This is very subjective. You will have to define "better". I suggest use HTML image sources as per the SO question so that at least retrieving those images is asynchronous otherwise your server call will take long time to retrieve inline image data for each item.

    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)