2011-09-02 83 views
0

我想打開一個覆蓋按鈕點擊。該按鈕與它關聯一個ajax調用,如果返回一個錯誤應該打開一個覆蓋,但在成功時覆蓋不會打開。jquery工具覆蓋:基於ajax響應打開覆蓋圖

會發生什麼情況是疊加打開,無論ajax響應中的成功/錯誤。它在按鈕點擊時打開,而不是在ajax響應上。我在這裏想念什麼?

這裏是我想...

//Overlay setup 
$('#PostQuestion').overlay({ 
    target: "#template" 
}); 

//Ajax call setup 
$('#PostQuestion').click(function() { 
    $.ajax({ 
     url: '/ask_away', 
     dataType: "json", 
     data: {question: 'something'}, 
     type: 'POST', 
     cache: false, 
     success: function(response) { 
      alert("It was a success"); 
     }, 
     error: function(request, error) { 
      $('#PostQuestion').data('overlay').load(); 
     } 
    }); 
}); 

<!-- HTML Here --> 
<div id="template">You got an error</div> 
<div id="PostQuestion">Ask Question</div> 

回答

1

原因的疊加顯示出成功的regardles/Ajax調用的錯誤是因爲此:

$('#PostQuestion').overlay({ 
    target: "#template" 
}); 

基本定義單擊處理程序#PostQuestion div打開覆蓋。所以,一旦你點擊PostQuestion div,你不僅發送ajax,而且還顯示覆蓋(正如我所說的上面的代碼片段的結果)。

要使其按要求工作,請檢查下面的代碼。再簡單一點 - 即使ajax調用返回200 OK,但沒有正確的json數據,錯誤處理程序將被使用,所以請在開發時記住這一點。

$(function() { 
      //Overlay setup 
      //select the overlay element in the jQuery selector and not the trigger element 
      $("#template").overlay(); 

      //Ajax call setup 
      $('#PostQuestion').click(function() { 
       $.ajax({ 
        url: '/ask_away', 
        dataType: "json", 
        data: {question: 'something'}, 
        type: 'POST', 
        cache: false, 
        success: function(response) { 
         alert("It was a success"); 
        }, 
        error: function(request, error) { 
         $("#template").data('overlay').load(); 
        } 
       }); 
      }); 
     })