2012-11-06 66 views
0

我有這個AJAX請求連接到newsletter-signup.html文件,然後搜索返回的data變量字符串「form-success」。 此字符串通過if語句中的(Django)模板應用,以標記表單已成功。Javascript/jQuery:如何讓這個AJAX請求運行得更快?

下面是搜索整個數據片段:

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

有搜索該數據更快的方法?或者,也許althoteger更好的方式來確定返回的數據是否成功註冊?

在此先感謝您的幫助。下面是完整的代碼:

$.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() { 
       }); 
      } 
     } 
    }); 
+0

在請求正在製作時顯示一個小的加載圖形。我非常懷疑是否還有其他方法可以使UI更快。 –

回答

1

我很懷疑你的data.indexOf通話過程中看到任何明顯的延遲。你感覺到的延遲可能是ajax調用本身,這將花費你的網絡所需的時間。沒有什麼可以在你的代碼中加快速度。

您還在與async: false進行通話,這意味着在大多數情況下,您在進行通話時鎖定瀏覽器,這不會帶來令人愉快的用戶體驗,並且可能會強調延遲。我強烈建議允許請求與某種「一刻」顯示不同步,允許用戶在等待時使用其他選項卡等。

(注意:請注意,async: false將是在jQuery 2.0中消失。)

+0

非常好,非常感謝'async:false' – shrewdbeans