weixin_33701251 2017-04-25 09:44 采纳率: 0%
浏览 144

Django中的Ajax请求缓慢

I have the following ajax request in my django template:

$('#subjects').on('change', function() {

    var subject = $('#subjects').find(":selected").text();

    $.ajax({
        type: "GET",
        url: "/classes/" + term + "/" + subject ,  // or just url: "/my-url/path/"
        dataType: "html",
        success: function(data) {
            $('#classes').html(data);
        }
    });

    //remove courses
    //remove overview

    //get courses for specified subject
    //put them under course
});

The "subject" id is for a select form like this:

<select size="7" class="form-control" id="subjects">
  {% for subject in subjects %}
    <option>{{ subject }}</option>
  {% endfor %}
</select>

So, when a subject is changed, I send an ajax request to the server so that I can get the classes for that subject from the database (as there are thousands of classes). However, this takes ~1 second. If a user simply arrows down my list of subjects, then tens of ajax requests will be fired off in a second, causing a backup and slowing down the data being displayed properly.

I tried aborting all previous ajax requests before sending another one, but the problem is the server will still process these, so it did not fix the problem.

Is there any way to speed this up, and somehow only take 1 second any time a user scrolls down to a subject? Or, is there another method that anyone would recommend?

Follow up question. Another way I just thought of would be to only send the ajax request if an option is selected for longer than 1 second. this would make it take 2 seconds which is fine. Is there a way to do this?

  • 写回答

2条回答 默认 最新

  • weixin_33726943 2017-04-25 10:08
    关注

    Do something like this enable/disable

    $('#subjects').on('change', function() {
    
        var subject = $('#subjects').find(":selected").text();
        document.getElementById('subjects').disabled=true
        $.ajax({
            type: "GET",
            url: "/classes/" + term + "/" + subject ,  // or just url: "/my-url/path/"
            dataType: "html",
            success: function(data) {
                $('#classes').html(data);
                document.getElementById('subjects').disabled=false
            }
        });
    
     #rest of code
    
    评论

报告相同问题?

悬赏问题

  • ¥15 vc6.0中想运行代码的时候总是提示无法打开文件是怎么回事
  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题