2013-03-28 109 views
1

有人可以告訴我如何確保下面的代碼只返回成功,當msg不爲空。jquery ajax獲得成功

即使msg.Text未定義,它偶爾會觸發success函數。

$.ajax({ 
    async: true, 
    url: url, 
    type: "GET", 
    data: params, 
    success: function (msg) { 
     if (msg.Text != undefined) { 
      $('#mediumText').val(msg.Text).blur(); 
     } else { 
      console.log("failed to load"); 
      return false; 
     } 
    } 
}); 
+0

檢查是否(msg!= null) –

+0

顯示您的回覆 – tamilmani

回答

1

您可以檢查響應的長度:

$.ajax({ 
    async: true, 
    url: url, 
    type: "GET", 
    data: params, 
    success: function (msg) { 
     if (msg.Text != undefined) { 
      if (msg.Text.Length > 0) { 
       $('#mediumText').val(msg.Text).blur(); 
      } else { 
       console.log("failed to load"); 
       return false; 
      } 
     } else { 
      console.log("failed to load"); 
      return false; 
     } 
    } 
}); 
1

您可以檢查長度和空OT沒有。

$.ajax({ 
async: true, 
url: url, 
type: "GET", 
data: params, 
success: function (msg) 
{ 
     if (msg.Text != null && msg.Text.Length > 0) 
     { 
      $('#mediumText').val(msg.Text).blur(); 
     } 
     else 
     { 
      console.log("failed to load"); 
      return false; 
     } 
} 
}); 
1

你可以只檢查一個falsey 值:

if (msg.Text) { 
    ... 
    } else { 
    ... 
    } 
1

如果msg.Text是不確定的,這並不意味着呼叫是不成功的,所以它是完全OK調用成功功能。您必須在成功回調中檢查msg.Text。

+1

非常感謝所有回覆。我現在已經解決了這個問題。 我正在使用帶有圖標的引導按鈕。當用戶點擊圖標而不是按鈕時發生問題。 不能相信我以前沒有注意到這一點。我只是相信這是我使用的ajax方法的問題。 再次感謝。 – user2219493