简体   繁体   English

Javascript / jQuery:如何使该AJAX请求运行得更快?

[英]Javascript /jQuery: How can I make this AJAX request run faster?

I have this AJAX request which connects to a newsletter-signup.html file, and then searches the returned data variable for the string "form-success". 我有这个AJAX请求,该请求连接到newsletter-signup.html文件,然后在返回的data变量中搜索字符串“ form-success”。 This string is applied via the (Django) template within an if statement to flag that the form was successful. 该字符串通过if语句中的(Django)模板应用,以标记表单成功。

Here is the snippet that searches the whole data: 以下是搜索整个数据的代码段:

if (data.indexOf('form-success') > 0) {

Is there a faster way to search this data? 有没有更快的方法来搜索这些数据? Or perhaps an althoteger much better way to determine if the returned data was a successful sign up? 或者,也许算是一种更好的方法来确定返回的数据是否成功注册?

Thanks in advance for your help. 在此先感谢您的帮助。 Here is the full code: 这是完整的代码:

    $.ajax({ url: '/newsletter-signup', type: 'GET', data: {email: emailVal},  async: false,
        success: function(data){
            // Returning 'form-success' in our data string indicates the sign up worked
            if (data.indexOf('form-success') > 0) {
                // open the success message in a modal window
                happyModal.open({ content: thankYouContent });
            } else {
                // if not successful re-load the contents, firing our standard error message
                theBtn.removeClass('disabled');
                $('.login-panel').load('/newsletter-signup','email=' + encodeURIComponent(emailVal), function () {
                });
            }
        }
    });

I very much doubt you're seeing any perceptible delay during the data.indexOf call. 我非常怀疑您在data.indexOf调用期间是否看到任何明显的延迟。 The delay you're perceiving is probably the ajax call itself, which will take as long as it takes on your network. 您感觉到的延迟可能是ajax调用本身,这将花费您网络上的所有时间。 Nothing you can do in your code to speed that up. 您无法在代码中做任何事情来加快速度。

You're also doing the call with async: false , which means in most cases you're locking up the browser while the call is in progress, which doesn't lead to a pleasant user experience and probably emphasizes the delay. 您还可以使用async: false来进行呼叫,这意味着在大多数情况下,您会在进行呼叫时锁定浏览器,这不会带来令人愉悦的用户体验,并且可能会强调延迟。 I'd strongly recommend allowing the request to be asynchronous with some kind of "one moment" display instead, allowing the user use other tabs while they're waiting, etc. 我强烈建议您允许该请求与某种“一时”显示异步进行,从而允许用户在等待时使用其他选项卡,等等。

(Side note: Be aware that async: false will be going away in jQuery 2.0.) (旁注:请注意, async: false将在jQuery 2.0中消失。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM