weixin_33721427 2015-06-03 10:59 采纳率: 0%
浏览 220

Django-ajax多个请求。

I am working with django-ajax module and I have some ajax based work:

views.py

@ajax
@login_required
def search_dist(request):
    dist_list = Distributor.objects.all()
    if request.method == 'GET':
        starts_with = request.GET['query']

    if starts_with:
        dist_list = Distributor.objects.filter(
            surname__istartswith=starts_with)
    return render(request, 'distributors/distributors_list.html', {'distributors': dist_list})

JS

var search = $('#search');
search.on('keyup', function() {
    window.setTimeout(function() {
        var query;
        query = search.val();
        ajaxGet('{% url "distributors:search_dist" %}', {
            'query': query
        }, function(content) {
            $('#distributors').html(content);
            set_favorite();
        })
    }, 1000);
});

It works just fine, but when I open my console I see that server makes too many requests for the same thing. For example: after I input 'Jhon' I see [03/Jun/2015 10:56:36]"GET /distributors/search_dist?query= HTTP/1.1" 200 25 times. Is something wrong with my code or it's just normal?

  • 写回答

1条回答 默认 最新

  • 七度&光 2015-06-03 12:52
    关注

    I see you've only used setTimeout. But you'll need to use clearTimeout function, too.

    search.on('keyup', function() {
        var timer;
        clearTimeout(timer);
        var query = search.val();
        timer = setTimeout(function() {
            ajaxGet('{% url "distributors:search_dist" %}', {
                'query': query
            }, function(content) {
                $('#distributors').html(content);
                set_favorite();
            })
        }, 1000);
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)