2012-04-10 71 views
0

我在javascript中有兩個if語句。我需要第二個if語句才能在第一個if語句執行後運行(我不能將兩個if語句放在一起,因爲第一個if語句有時候會執行,否則第一個語句必須在第二個語句運行之前檢查。 )jQuery等待if語句完成

我該怎麼做?

下面是代碼BTW:

if($('#suggestion-'+change).html() == null) 
    {  
     $.ajax({ 
      type: 'post', 
      dataType: 'html', 
      url: '/suggestion/ajax-change/', 
      data: {type: change}, 
      success: function(result,status) 
      { 
       $('#profile_suggestion .content_wrapper').prepend(result); 
      } 
     }); 
    } 

    if(active != change) 
    { 
     var panelShow = '#suggestion-' + change; 
     var panelHide = '#suggestion-' + active; 
     var dirShow = ''; var dirHide = ''; 

     switch(active) 
     { 
      case 'compatibility': 
       dirHide = 'left'; 
       switch(change) 
       { 
        case 'mutual': 
         dirShow = 'right'; 
         break; 
       } 
      case 'mutual': 
       switch(change) 
       { 
        case 'compatibility': 
         dirHide = 'right'; 
         dirShow = 'left'; 
       } 
     } 
     $(panelHide).hide("slide", { direction: dirHide }, 1000); 
     $(panelShow).show("slide", { direction: dirShow }, 1000).removeClass('fader'); 
     $(panelHide).addClass('fader'); 
     active = change; 
    } 

回答

0

嗯,你可以讓第二個到一個函數,並調用它在成功?我很抱歉,如果我誤解了你的問題..

或者你也可以做到這一點

$("something").bind('update', function() { do something you want to do }); 

    $.ajax({ 
     type: 'post', 
     dataType: 'html', 
     url: '/suggestion/ajax-change/', 
     data: {type: change}, 
     success: function(result,status) 
     { 
      $('#profile_suggestion .content_wrapper').prepend(result); 
     }, 
     complete: function() 
     { 
      $("something").trigger('update'); 
     } 
    }); 
+0

嗨,感謝您的回覆。這兩個if語句彼此獨立,所以它們不能在彼此之內。它只是第二個if語句必須在第一個語句之後運行(有時第一個if語句無論如何都是錯誤的,但仍然需要先檢查!) – user1083320 2012-04-10 01:29:37

+0

您還可以考慮使用complete ..並使用trigger()導致產生適當的事件。 – 2012-04-10 01:42:07

1

添加async: false到Ajax調用。

+0

那沒用! – user1083320 2012-04-10 01:31:34

+0

它應該是異步的,你是否複製我的錯字? :) – 2012-04-10 01:35:21

+1

aysnc AJAX電話是壞消息熊。 – iambriansreed 2012-04-10 01:50:05

1

您對回調和異步代碼有誤解。

您會希望將2nd if語句放入成功回調中。

$.ajax({ 
    type: 'post', 
    dataType: 'html', 
    url: '/suggestion/ajax-change/', 
    data: { 
     type: change 
    }, 
    success: function(result, status) { 
     $('#profile_suggestion .content_wrapper').prepend(result); 
     if (active != change) { 
      var panelShow = '#suggestion-' + change; 
      var panelHide = '#suggestion-' + active; 
      var dirShow = ''; 
      var dirHide = ''; 
      ..... 
     } 
    } 
});​ 

因爲一個xhr(AJAX)請求具有的時間內沒有規定量響應則不能準確地猜測當在accoradance地運行的代碼的另一個塊到它的響應。您必須在完成的回調中執行代碼,在此例中爲success

與其將第2條if語句的實際代碼放入成功中,您應該考慮放置到另一個函數中。

+0

ajax並不需要一直被調用!所以我想分開保存兩個if語句,以防止額外調用ajax。 – user1083320 2012-04-13 00:58:49