jQuery 表单提交前的动画不工作

jQuery animation BEFORE form submission not working

当我尝试将 jQuery click 动画添加到我的提交按钮时,它会启动动画,但很快就会重置,因为表单提交并刷新了页面。如果表单被 div 包裹,动画工作正常,但在动画完成后表单不会提交。我怎样才能让它在动画完成后提交表单并防止动画在表单提交后重置。我是 PHP 和 jQuery 的新手,不知道该怎么做。这是我目前所拥有的:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
    <style type="text/css">
        body
        {
            background-color: lightgrey;
            height: 100%;
            width: 100%;
            overflow: hidden;
        }
        .PSolCanvas
        {
            transform: translate(-50%, -40%);
            z-index: 1;
            position: absolute;
            left: 50%;
            top: 88.5%;
            background-color: transparent;
            min-height: 100%;
        }
        .PSol
        {
            width: 120px;
            height: 120px;
            margin: 0 auto;
            -webkit-border-radius: 100%;
            -moz-border-radius: 100%;
            border-radius: 100%;
            font: 15px arial;
            color: black;
            border: 1px solid lightgray;
            background: #20AC20;
        }
    </style>
    <script rel = "javascript" type = "text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script type='text/javascript'>
        $(document).ready(function(){
            $(".PSol").click(function() {
                $(".PSolCanvas, .TSolCanvas").animate({top: "50%"});
            });
        });
    </script>
</head>
<body>
<?php
$username = "username";
$password = "password"; 
$host = "host";
$db = $username;

if(isset($_POST['PSol']))
{
    $connection = mysqli_connect($host, $username, $password, $db);
    $sql = "UPDATE table SET column='' WHERE id = 1";
    if (mysqli_query($connection, $sql)) {
        echo "Record successfully changed.";
    }
    else{
        echo "Error: " . $sql . "<br>" . mysqli_error($connection);
    }
    mysqli_close($connection);
    echo "<p>Disconnected from server: ".$host."</p>";
}
?>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method = "post" class = "PSolCanvas">
        <input type = "submit" name = "PSol" class = "PSol" value = "P"/>
    </form>
</body>
</html>

您将想要尝试对动画执行 callback,以便在完成后提交。类似于:

<script type='text/javascript'>
    $(document).ready(function(){
        $(".PSol").click(function(e) {
            // You will want to prevent the natural submission of the form
            e.preventDefault();
            // Notice the function attached to the `.animate()`. 
            // This will fire after the animation is done.
            $(".PSolCanvas, .TSolCanvas").animate({top: "50%"},function(){
                $('.PSolCanvas').submit();
            });
        });
    });
</script>

编辑: 这是一个 ajax 版本,我让它有点复杂,因为您可能想在您网站的其他地方重复使用 ajax ,但您实际上只需要 this.ajax 部分中的内容。脚本的顺序很重要,因为这个特定示例调用自身 (为 ajax 调用另一个页面会更好)。其他所有内容 (将内容分成各自的页面) 只是建议:

/config.php

<?php
// Make some defines
define("DB_USERNAME",'username');
define("DB_PASSWORD",'password');
define("DB_HOST",'host');
define("DB_DATABASE",'database');

/functions/myfunctions.php

<?php
// Make some functions to make things cleaner/universal
function connection()
    {
        return mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
    }
// Make a function that you can reuse
function updateTable($val,$con)
    {
        return (mysqli_query($con, "UPDATE table SET column='' WHERE id = {$val}"));
    }

/index.php(不管这个页面叫什么)

<?php
// Include above assets
require_once(__DIR__.'/config.php');
require_once(__DIR__.'/functions/myfunctions.php');
// This should run only on the ajax call
if(!empty($_POST['PSol'])) {
    // Get the connection
    $con        =   connection();
    // Set common text
    $disc       =   "<p>Disconnected from server: ".DB_HOST."</p>";
    // Run the update
    if(updateTable(1,$con))
        // If success
        $response   =   json_encode(array('msg'=>"Record successfully changed. {$disc}"));
    else
        // If fail
        $response   =   json_encode(array('msg'=>"Error: {$sql}<br>".mysqli_error($con).$disc));
    // Close connection
    mysqli_close($con);
    // Stop further processing of page
    // If you don't stop processing, you will send back the rest of the 
    // page below and will malform your json
    die($response);
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<style type="text/css">
    body
    {
        background-color: lightgrey;
        height: 100%;
        width: 100%;
        overflow: hidden;
    }
    .PSolCanvas
    {
        transform: translate(-50%, -40%);
        z-index: 1;
        position: absolute;
        left: 50%;
        top: 88.5%;
        background-color: transparent;
        min-height: 100%;
    }
    .PSol
    {
        width: 120px;
        height: 120px;
        margin: 0 auto;
        -webkit-border-radius: 100%;
        -moz-border-radius: 100%;
        border-radius: 100%;
        font: 15px arial;
        color: black;
        border: 1px solid lightgray;
        background: #20AC20;
    }
</style>
<script rel = "javascript" type = "text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
    // This is an object to contain your ajax app
    var AjaxEngine  =   function()
        {
            // Set some common containers
            var url;
            var useURL;
            // This function will set where to point the ajax call
            this.useUrl =   function(url)
                {
                    useURL  =   url;
                    return this;
                }
            // This is the actual jQuery ajax call
            this.ajax   =   function(useData,func)
                {
                    // Create jQuery ajax
                    $.ajax({
                        // Use our previously-set url
                        url: useURL,
                        // This is the data to send to our page
                        data: useData,
                        // Send the data by POST method
                        type: 'post',
                        // When the post is successful
                        success: function(response){
                                // Use an anonymous function
                                func(response);
                            }
                    });
                }
        }

    $(".PSol").click(function(e) {
        // Set the form
        var thisForm    =   $('.PSolCanvas');
        // Get the values from the form
        var useData =   thisForm.serialize();
        // Stop from submission
        e.preventDefault();
        $(".PSolCanvas, .TSolCanvas").animate({top: "50%"},function(){
            // Create instance of our ajax object
            var Ajaxer  =   new AjaxEngine();
            // Set the url (in this case we are getting the action=""
            // from the form tag)
            // The "useData" param is the form data
            // The second param is the function we want to run when
            // the ajax successful
            Ajaxer.useUrl(thisForm.attr('action')).ajax(useData,
                function(response) {
                    // Try, just incase the code produces an error and
                    // malforms the json response 
                    try {
                        // Parse the return json_encode()
                        var json    =   JSON.parse(response);
                        // Send the message to the container
                        $('#writespot').html(json.msg);
                    }
                    catch (Exception) {
                        // This will catch any error, so
                        // make sure your console is open to review
                        console.log(Exception.message);
                        console.log(response);
                    }
                });
        });
    });
});
</script>
</head>
<body>
    <!-- This is where the response message will be written to -->
    <div id="writespot"></div>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" class="PSolCanvas">
        <input type="submit" name="PSol" value="P" class="PSol" />
        <input type="hidden" name="PSol" value="P"/>
    </form>
</body>
</html>

您想在动画完成后提交表单运行。为此,您需要阻止默认 'submit',然后在 jQuery 上使用回调函数添加自己的回调函数,动画 call.This 将仅在动画完成后调用 .submit()。类似的东西(请注意我还没有机会检查这段代码,但它应该给你一个大概的想法:

  $(document).ready(function(){
        $(".PSol").click(function(e) {
            e.preventDefault();
            $(".PSolCanvas, .TSolCanvas").animate({top: "50%"},
                function() {
                $("form").submit(); 
                }
             );
        });
    });