AJAX将jQuery脚本插入到结果div中

时间:2016-02-21 20:37:37

标签: javascript php jquery html ajax

我想要实现的是,如果没有提交任何内容,则会显示该表单。所以我将表单html添加到变量中,然后在html中回显变量。

然而,自从我在#results div中实现了AJAX之后。它还导出jquery.js和我的ajax脚本。

如果我删除显示表单的PHP else代码,我根本不会看到该表单。

enter image description here

那么有人会如何确保js脚本不会插入到它们不应该的位置?

PHP:     

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

<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>





<?php echo $final_content ?>

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

    </body>


</html>

1 个答案:

答案 0 :(得分:0)

exit();之后$conn->close();正上方添加else

这将确保在您输出结果后,您不会继续使用script标记和{{1}输出完整HTML页面的其余代码(未包含在您的问题中)等等......

显然,显示代码不在<div id="results">块内,而是在<{em> else块之后