简体   繁体   中英

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". This string is applied via the (Django) template within an if statement to flag that the form was successful.

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. The delay you're perceiving is probably the ajax call itself, which will take as long as it takes on your network. 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. 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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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