2011-03-08 120 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'  
    }); 
}); 

我甚至为你扔了一个漂亮的加载图标。