2011-03-08 117 views
0

我有兩個按鈕,Save和Unsave。通常,我每個人都去一個PHP的帖子頁面,並刷新頁面。如果您點擊保存,頁面將被刷新,只有Unsave會顯示 - 反之亦然。使用jQuery和Ajax切換按鈕

我試圖用Ajax和jQuery來做到這一點。基本上,我有這些:

​​

下面是通常會切換他們PHP:

//$thisIsSaved would return 1 if the coupon has been saved and 0 if not 
     $hasSaved = "inline"; 
     $youveSaved = "none"; 
     if($thisIsSaved > 0 && $_SESSION["loggedIn"] == 1) 
      { 
       $hasSaved = "none"; 
       $youveSaved = ""; 
      } 
     elseif($thisIsSaved == 0 && $_SESSION["loggedIn"] == 1) 
      { 
       $hasSaved = ""; 
       $youveSaved = "none"; 
      } 
     else 
      { 
       $hasSaved = "none"; 
       $youveSaved = "none"; 
      } 

我怎麼能這樣做不需要刷新頁面,用純阿賈克斯+ jQuery的?

回答

3

你可以很容易地用jQuery和jQuery的$.ajax()方法做到這一點。

見活生生的例子:http://jsfiddle.net/rtE9J/11/

HTML

<button id="save">Save</button> 
<button id="unsave">Unsave</button> 
<div id="result"></div> 

CSS

#unsave{display:none} 

JS

$('#save, #unsave').click(function(){ 

    //maintain reference to clicked button throughout 
    var that = $(this); 

    //disable clicked button 
    $(that).attr('disabled', 'disabled'); 

    //display loading Image 
    $('#result').html('<img src="http://blog-well.com/wp-content/uploads/2007/06/indicator-big-2.gif" />'); 

    //Make your AJAX call 
    $.ajax({ 
     url: 'changeSave.php', 
     data: {action: $(this).attr('id')}, 
     success: function(d){ 

      //re-enable the button for next time 
      $(that).attr('disabled', ''); 

      //Update your page content accordingly. 
      $('#result').html(d); 

      //Toggle the buttons' visibilty 
      $('#save').toggle(); 

      //Toggle the buttons' visibilty 
      $('#unsave').toggle(); 

     }, 
     type: 'POST'  
    }); 
}); 

我甚至爲你扔了一個漂亮的加載圖標。