2012-04-13 28 views
0

用下面的代碼:IE和Chrome瀏覽器忽略jQuery的調用之前阿賈克斯後

  $('#langHref').html("Translating...").css("color","#FF9933"); 

      jQuery.ajax({ 
       type: "post" 
       , url: someUrl 
       , data: { "text": $('body').html() } 
       , async: false 
       , success: function (data, status) { 
        $('body').html(data);      
       }, 
       error: function() { 
        alert('We are sorry, there was an error in the translation service.'); 
        //console.log("ERROR", arguments); 
       } 
      }); 

      $('#langHref').html("Select Language").css("color",""); 
     } 

我有一個<a>標籤與「langHref」的ID,這裏的想法是,之前的AJAX被稱爲鏈接文字設置爲「翻譯...」,其顏色變爲橙色。 ajax完成後,鏈接文本變回標準的「選擇語言」。

這在FF中運行良好,但在IE和Chrome中失敗。我已經嘗試了所有beforeSend jQuery選項和ajaxSend事件,以在ajax熄滅之前嘗試設置它,但無濟於事。

如果關閉async:false,那麼顯然它會立即將文本更改回「Select a language」,並且您看不到它的工作。我也嘗試了async:true,並在beforeSend中放置了「Translating ....」調用,這在我試過的任何瀏覽器中都不起作用。

想法?

回答

0

我想你想beforeSend添加到您的AJAX請求,這樣做有像這樣:

beforeSend: function (xhr) { 
    $('#langHref').html("Translating...").css("color","#FF9933"); 
} 

和完整的方法太:

complete : function(jqXHR, textStatus) { 
      $('#langHref').html("Select Language").css("color",""); 
}, 
+0

幹得好,我嘗試了beforeSend,但我沒有嘗試完整。現在正常工作! – Synergyauto 2012-04-14 00:12:10

0

可以通過改變 async完成屬性爲true 並將最後一行放入完成的事件中。事情是這樣的:

  jQuery.ajax({ 
       type: "post" 
       , url: someUrl 
       , data: { "text": $('body').html() } 
       , async: true 
       , success: function (data, status) { 
        $('body').html(data);      
       }, 
       error: function() { 
        alert('We are sorry, there was an error in the translation service.'); 
        //console.log("ERROR", arguments); 
       }, 
       completed:function(){ 
        $('#langHref').html("Select Language").css("color",""); 
       }, 
       beforeSend:function(){ 
       $('#langHref').html("Translating...").css("color","#FF9933"); 
       } 
      }); 

也許正在發生的事情是,改變UI,因爲jQuery的AJAX功能是異步它阻止用戶界面,因此它不能被改變之前。