使用jQuery和Ajax切换按钮

时间:2011-03-08 19:47:14

标签: jquery ajax

我有两个按钮,Save and Unsave。通常情况下,我每个人都去了一个PHP帖子页面并刷新了页面。如果单击“保存”,页面将刷新,仅显示Unsave - 反之亦然。

我正在尝试使用Ajax和jQuery。基本上,我有这些:

<span style="display: <?php echo $youveSaved; ?>"><input type="button" value="Unsave" onClick="$.post('php/removeSave.php', $('#removeSave').serialize());$('#jqs').attr('value', 'Save');" id="jqs"/></span>
<span style="display: <?php echo $hasSaved; ?>"><input type="button" value="Save" onClick="$.post('php/saveCoup.php', $('#saveCoup').serialize());$('#jqs').attr('value', 'Unsave');" id="jqs"/></span>

这是通常会切换它们的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";
            }

如果没有页面刷新,我怎么能用纯Ajax + jQuery做到这一点?

1 个答案:

答案 0 :(得分: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'     
    });
});

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