【问题标题】:Jquery ajax sends multiple responses back in Chrome while in FF sends only one responseJquery ajax 在 Chrome 中发送多个响应,而在 FF 中只发送一个响应
【发布时间】:2013-07-23 11:43:02
【问题描述】:

问题是,当有新消息时,不是只提醒一次,而在 Chrome 中,它会以相同的值提醒 5-8 次。相比之下,这些代码与 FF 配合得很好,它只会发出一次警报。如何修复代码以支持 Chrome。 HTML:

setInterval(function() {
    $.get('/restaurant/get_msg_notification',{},function(data){
        alert(data)
    })
}, 1000)

查看:

def get_msg_notification(request):    
    while True:
        # check is there any new messages ?
        msg = Message.objects.filter(receiver = user, notify = False)
        if( len(msg)==0 and patient<5):
            time.sleep(5)
            patient+=1
        else:
            break
    if( len(msg) > 0):
        data = serializers.serialize('json', msg)
        msg.update(notify = True)
        return HttpResponse(data, mimetype="application/json")
    else:
        return HttpResponse("")

【问题讨论】:

  • 现在我尝试删除“患者”变量,所以它根本不是长轮询。该方法给了我一个正确的结果(只响应一次)。但是,如果没有长轮询,ajax 需要每秒发送一个请求,这很昂贵。
  • 从这个链接中找到了长轮询的很好的解释和解决方案。 techoctave.com/c7/posts/…

标签: jquery ajax django google-chrome


【解决方案1】:

实际上,Firefox 似乎是无法正常工作的那个。请尝试以下代码:

def get_msg_notification(request):    
    while True:
        # check is there any new messages ?
        msg = Message.objects.filter(receiver = user, notify = False)
        if(patient < 5):
            time.sleep(5)
            patient+=1
        else:
            if (len(msg) != 0):
                msg.update(notify = True)
            break

    data = serializers.serialize('json', msg)
    return HttpResponse(data, mimetype="application/json")

【讨论】:

  • 我忘了在 while 循环之外写 if 条件到问题中。现在我已经将该条件包含在问题中。对了,你觉得FF为什么不能正常工作?
猜你喜欢
  • 2020-07-25
  • 2021-12-22
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 2018-10-23
  • 2021-12-11
  • 2021-06-05
  • 1970-01-01
相关资源
最近更新 更多