2013-12-11 128 views
1

我通過這個很多帖子去了,但沒有找到任何解決方案爲我工作 - 清理代碼:廣東話訪問.post的可變

$('#form-new').submit(function(e){ 
    e.preventDefault(); 

    $curForm = $(this); 
    $textbox = $('.new-box' ,this); 

    window.tmp_input_ok = false; 

    var wasError = false; 
    if($.trim($textbox.val()) == ""){ 
     wasError = true; 
    }  

    if(wasError){ 
     //possible message 
    } else{ 

     var jqxhr = $.post(
     $(this).attr('action'), 
     $(this).serialize(), 
     function(data, textStatus, jqXHR){ 

      if(data=="200"){ 
      console.log('post OK'); //this shows in console! 
      window.tmp_input_ok = true; 
      } else{ 
      console.log('not OK');  
      } 

     } 
    ).fail(function() { 
     console.log('POST fail)'); 
     });  

    } 

    //however, window.tmp_input_ok is false here so the textbox does not empty: 
    if(window.tmp_input_ok == true) $textbox.val(''); 
     else console.log('input not ok :('); //and this is outputted to console 

    }); 

的淵源,也只是一個var tmp_input_ok = false初始化,然後工作與tmp_input_ok變量,但它沒有工作,所以我嘗試了全球窗口...也不管用...我開始絕望。

+6

'$ .post()'調用是異步的。該函數會立即返回,但是直到收到HTTP響應時纔會調用傳入的回調。 – Pointy

回答

2

您的if語句在調用完成之前執行。

$.post是,而後期的處理

您已經使用.fail()一個異步調用和代碼的其餘部分繼續,你可以添加.always(),如果你想在完成總執行你的if語句或將其添加到您.success()如果你只是要檢查它的時候調用成功,與此類似:

if (wasError) { 
    //possible message 
} else { 
    var jqxhr = $.post($(this).attr('action'), $(this).serialize(), function (data, textStatus, jqXHR) { 
     if (data == "200") { 
      console.log('post OK'); //this shows in console! 
      window.tmp_input_ok = true; 
     } else { 
      console.log('not OK'); 
     } 

     // either add it here if you only want to process it on success 
     if (window.tmp_input_ok == true) $textbox.val(''); 
     else console.log('input not ok :('); 
    }).fail(function() { 
     console.log('POST fail)'); 
    }).always(function(){ // or add it here if you always wan to execute on completion regardless of fail or success 
     if (window.tmp_input_ok == true) $textbox.val(''); 
     else console.log('input not ok :('); 
    }); 
} 
+1

爲了更好的可讀性和一致性,我將成功處理程序代碼放入'.done()'函數中,就像'.fail()'和'.always()'一樣。 – Simon

+0

啊我忘了異步處理....這是問題,讓我檢查出來... –

+0

它正在工作! :)(你只是拯救了我的生命:P),順便說一句 - 總是() - 它總是在成功後執行並且失敗得到處理? –

1

您XHR請求有回調的onSuccess的原因是因爲調用是異步的。

就拿這個代碼簡單位:

$.get(
    '/foo', 
    function(){ 
     alert("data received"); 
    } 
) 

alert ("End of script reached"); 

成功回調設置的東西時,成功接收到請求時,將調用,而不是在該行代碼被讀瀏覽器。

通常您會在「數據收到」警報之前看到「達到腳本結束」警報,因爲完整的XHR請求需要超過100毫秒的時間,而閱讀這些少數幾行文件只需要幾分鐘。

取決於具有狀態響應的代碼必須由回調調用。有很多方法可以爲我做詳細說明。