2017-05-06 59 views
1

嗨,我創建的自動完成seacrh重定向後,搜索的Django

的Javascript

jQuery(function() { 
    $("#id_input").on('keyup', function(){ 
     var value = $(this).val(); 
     $.ajax({ 
      url: "{% url 'ajax_autocomplete' %}", 
      data: { 
       'search': value 
      }, 
      dataType: 'json', 
      success: function (data) { 
       list = data.list; 
       $("#id_input").autocomplete({ 
       source: list, 
       minLength: 3 
       });  
      } 
     });   
    }); 
    }); 

查看:

def autocomplete_search(request): 
     if request.is_ajax(): 
      game = None 
      try: 
       game = Game.objects.get(name=request.GET.get('search', None)) 
      except: 
       pass 
      if game is not None: 
       result = redirect('games') 
      else:  
       queryset = Game.objects.filter(name__startswith=request.GET.get('search', None)) 
       list = [] 
       for i in queryset: 
        list.append(i.name) 
       data = { 
        'list': list, 
       } 
       result = JsonResponse(data) 
      return result 

但當game is not None它只是響應頁面,Ajax請求也沒有重定向。但我想停止請求時,game != None和加載我需要的網頁。哪裏不對?

+0

看看這個post:http://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery -ajax-call – karthikr

回答

0

THX爲karthikr我做到了下一方式

def autocomplete_search(request): 
     if request.is_ajax(): 
      game = None 
      try: 
       game = Game.objects.get(name=request.GET.get('search', None)) 
      except: 
       pass 
      if game is not None: 
       data = { 
        'redirect': '/link-to-redirect/' 
       } 
       result = redirect('games') 
      else:  
       queryset = Game.objects.filter(name__startswith=request.GET.get('search', None)) 
       list = [] 
       for i in queryset: 
        list.append(i.name) 
       data = { 
        'list': list, 
       } 
       result = JsonResponse(data) 
      return result 

和jQuery旁邊的更改方式:

 $.get({% url 'ajax_autocomplete' %}, { 
       data: $('#search-game').val() 
      }, function (response) { 
       if (response.redirect !== undefined) { 
        top.location.href=response.redirect; 
       } else { 
       list = response.list; 
       $("#search-game").autocomplete({ 
        source: list, 
        minLength: 2 
       }); 
       } 
      }); 
0

因爲你正在將重定向函數分配給一個變量,它不會以這種方式工作。 你只需要在條件的每一端返回。

嘗試這樣的事:

def autocomplete_search(request): 
     if request.is_ajax(): 
      game = None 
      try: 
       game = Game.objects.get(name=request.GET.get('search', None)) 
      except: 
       pass 
      if game is not None: 
       return redirect('games') 
      else:  
       queryset = Game.objects.filter(name__startswith=request.GET.get('search', None)) 
       list = [] 
       for i in queryset: 
        list.append(i.name) 
       data = { 
        'list': list, 
       } 
       return JsonResponse(data) 
+0

我試着用2返回相同的。 – Hellbea