AJAX不会提交数据

时间:2016-02-21 20:00:56

标签: javascript php jquery ajax

我只是在学习AJAX。本周我们的任务是使用Ajax提交表单。但是我似乎无法弄清楚我做错了什么,因为它不会提交。

PHP本身就可以运行。如果禁用JavaScript,它需要作为备份选项提供。

<?php

    $final_content='';

if( isset($_POST["u_name"]) && isset($_POST["u_lastname"]) && isset($_POST["u_email"]) ){

    $servername = "";
    $username = "";
    $password = "";
    $dbname = "";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    }

    $sql = "INSERT INTO testTable (Name, Lastname, Email)

    VALUES ('".$_POST["u_name"]."','".$_POST["u_lastname"]."','".$_POST["u_email"]."')";


    if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
    } else {
    echo "Error: " . $sql . "<br>" . $conn->error."";
    }

    $conn->close();


}else {
    $final_content = '<form action="script.php" method="post" id="user_form">

    <input type="text" name="u_name" placeholder="Name" id="user_name"> <br>
    <input type="text" name="u_lastname" placeholder="Lastname" id="user_lastname"> <br>
    <input type="email" name="u_email" placeholder="Email" id="user_email"> <br>

    <input type="submit" value="Submit" name="submit">
    </form>';
}
?>

<html>
    <head>

        <script type="text/javascript" src="jquery-1.11.2.min.js"></script>


        <script>
        $(document).ready(function(){

            //Set form variable
            var form = $("#user_form");

            form.submit(function(event){

                //Set data variables
                var user_name = $("#user_name").val();
                var user_lastname = $("#user_lastname").val();
                var user_email = $("#user_email").val();

                    //Check if values are set
                    if( ($.trim(user_name) != "") && ($.trim(user_lastname) != "") && ($.trim(user_email) != "") ){

                        $.post("script.php", {u_name: user_name}, {u_lastname: user_lastname}, {u_email: user_email}, function(data){

                            $("#results").html(data);   

                        });
                    }

                event.preventDefault();
            });

        });
        </script>

    </head>

    <body>



<div id="results"></div>

<?php echo $final_content ?>

    </body>


</html>

1 个答案:

答案 0 :(得分:0)

试试这个:

 $.post("script.php", {u_name: user_name}, {u_lastname: user_lastname}, {u_email: user_email}, function(data){
       $("#results").html(data);   
});

使用以下代码替换上述行:

$.post("script.php", {u_name: user_name,u_lastname: user_lastname,u_email: user_email}, function(data){
        $("#results").html(data);   
});

有关$.post()功能的不同选项的更多详细信息,请参阅以下链接: http://api.jquery.com/jquery.post/