Javascript的不aynchronously继续超越AJAX调用 [英] Javascript not proceeding aynchronously beyond AJAX call

查看:127
本文介绍了Javascript的不aynchronously继续超越AJAX调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户presses在我的应用程序中的进程按钮,我想应用程序触发一个AJAX请求,然后立即将用户重定向到另一个屏幕,而无需等待AJAX​​请求的结果。我相信我有codeD也适当,但我注意到屏幕正在等待AJAX​​来重定向前完成。我失去了一些东西在下面?

  $('#过程BTN)。在('点击',函数()
{
    //关闭进程和放大器;取消按钮prevent
    //双提交或中断
    $('#取消-BTN)addClass(已禁用)。
    $(本).addClass(已禁用);

    //触发AJAX要求来处理在服务器端上传文件
    $阿贾克斯({
        网址:$('#形式')ATTR(行动),
        类型:'后',
        数据:$('#形式')序列化()。
        成功:函数(){
            //成功
        }
    });

    //将用户重定向到浏览列表
    //这一行没有被立即调用 - 
    //这是被AJAX返回后,才调用
    window.location.replace(www_root +首页/指数');
});
 

解决方案

由于您有这方面的处理程序挂接到该按钮是一个表单提交按钮(根据您的评论),你是不是preventing的默认行为该按钮,那么表单提交会立即发生,当提交返回时,它会不管你的code试图做改变页面。

所以,问题是,返回的形式提交了克服你的code试图做的事情。


您可能会活有点危险重定向之前,你的AJAX调用已完成。这是可能前TCP缓冲区已实际发送的TCP往往发送缓冲区,以收集连续的数据为普通报文之前,延时小的浏览器可能下降的AJAX连接。这将是更加安全或者重定向一个短暂停后,或重定向的完整事件,则无论阿贾克斯成功的调用。


如果你真的想这样做重定向之前Ajax调用完成后,您可以在此code(如设定为500毫秒如图所示)的超时值试验,看看有什么可以可靠地工作在多个浏览器:

  $('#过程BTN)。在('点击',功能(五){
    // prevent默认窗体发布
    即preventDefault();

    //关闭进程和放大器;取消按钮prevent
    //双提交或中断
    $('#取消-BTN)addClass(已禁用)。
    $(本).addClass(已禁用);

    //触发AJAX要求来处理在服务器端上传文件
    $。员额($('#形式')ATTR(行动),$('#形式')序列化());

    //将用户重定向到浏览列表
    //这个被称为一个短暂的延迟后,试
    //获取表单Ajax调用发送的,而不是等待的服务器响应
    的setTimeout(函数(){
        window.location.replace(www_root +首页/指数');
    },500);
});
 

另外,请注意,我添加了一个即preventDefault()并添加了电子参数事件处理程序以确保表单不贴在默认情况下,只能由您的AJAX code。

和,超时时间在这里设置为500毫秒。你需要的是足够的时间在主机的TCP基础设施,以启动重定向前将所有的表单数据。我看到一个提一个文件上传你的意见。如果这种形式实际上是上传文件时,可以采取的方式,方法大于500毫秒。如果只是发送了一些表单域,应该去pretty的迅速假设没有连接打嗝。

警告:这样做,这样是不是将数据传输到服务器的100%可靠的方法。这里很容易被某些条件下需要更长的时间比平常只是用您的服务器或服务器连接,可以随时需要更长的时间来响应初始连接之前的数据可以发送到它之前做一个DNS查找。唯一的100%可靠的方法是等到Ajax调用已成功为其他地方提到的。

您也许可以例如有两全其美(可靠性+响应速度快),如果你改变了你的服务器处理Ajax调用的方式,这样只要它接收到的数据,它返回一个成功的响应(后毫秒接收数据),然后后,已发回成功的响应,以便在浏览器就可以可靠地执行它的重定向,它需要它的2-3分钟来实际处理数据。请记住,你不给等待,直到你完成处理返回响应该请求。然后,你知道服务器已经接收到的数据,但浏览器不必等待处理时间。如果你并不总是希望这个Ajax调用工作方式,您可以将参数传递给Ajax调用是否要快速响应或不指示服务器。

When the user presses the 'Process' button on my application, I would like the application to trigger an AJAX request and then immediately redirect the user to another screen without waiting for the results of the AJAX request. I believe I have coded it appropriately but I notice that the screen is waiting for the AJAX to finish before redirecting. Am I missing something below?

$('#process-btn').on('click', function() 
{
    // disable the process & cancel buttons to prevent 
    // double submission or interruption
    $('#cancel-btn').addClass('disabled');
    $(this).addClass('disabled');

    // trigger the AJAX require to process the uploaded file on the server side
    $.ajax({
        url: $('#form').attr('action'),
        type: 'post',
        data: $('#form').serialize(),
        success: function() {
            //on success
        }
    });

    // redirect the user to view list
    // this line is not being called immediately - 
    // this is being called only after AJAX returns
    window.location.replace( www_root + 'Home/index' );
});

解决方案

Because the button you have this handler hooked to is a submit button for a form (per your comments) and you aren't preventing the default behavior of that button, then the form submit will happen immediately and when the submit returns, it will change the page regardless of what your code tries to do.

So, the issue is that the returned form submit was overcoming what your code was trying to do.


You may be living a little dangerously by redirecting before your ajax call has finished. It's possible the browser could drop the ajax connection before the TCP buffers had actually been sent as TCP often has a small delay before sending buffers in order to collect consecutive data into common packets. It would be much safer to either redirect after a short timeout or redirect on the complete event which will be called regardless of ajax success.


If you really want to do the redirect BEFORE the ajax call has completed, you can experiment with the timeout value (shown here as set to 500ms) in this code to see what works reliably in multiple browsers:

$('#process-btn').on('click', function(e) {
    // prevent default form post
    e.preventDefault();

    // disable the process & cancel buttons to prevent 
    // double submission or interruption
    $('#cancel-btn').addClass('disabled');
    $(this).addClass('disabled');

    // trigger the AJAX require to process the uploaded file on the server side
    $.post($('#form').attr('action'), $('#form').serialize());

    // redirect the user to view list
    // this being called after a short delay to "try"
    // to get the form ajax call sent, but not "wait" for the server response
    setTimeout(function() {
        window.location.replace( www_root + 'Home/index' );
    }, 500);
});

Also, note that I've added an e.preventDefault() and added the e argument to the event handler to make sure the form is not posted by default, only by your ajax code.

And, the timeout time is set here to 500ms. What you need is enough time for the TCP infrastructure in the host computer to send all your form data before you start the redirect. I see a mention of a "file upload" in your comments. If this form is actually uploading a file, that could take way, way longer than 500ms. If it's just sending a few form fields, that should go pretty quickly assuming there are no connection hiccups.

Caveat: Doing it this way is not the 100% reliable way of getting data to your server. There can easily be some conditions where it takes longer than usual just to do a DNS lookup before connecting with your server or your server could momentarily take longer to respond to the initial connection before data can be sent to it. The only 100% reliable way is to wait until the ajax call has succeeded as mentioned elsewhere.

You could perhaps have the best of both worlds (reliability + fast response) if you changed the way your server processes the ajax call so that as soon as it has received the data, it returns a successful response (e.g. in milliseconds after receiving the data) and then after it has sent back the successful response so the browser can then reliably do its redirect, it takes it's 2-3 minutes to actually process the data. Remember, you don't gave to wait until you are done processing the request to return a response. Then, you know that the server has received the data, but the browser doesn't have to wait for the processing time. If you don't always want this ajax call to work that way, you can pass an argument to the ajax call to instruct the server whether you want the fast response or not.

这篇关于Javascript的不aynchronously继续超越AJAX调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆