jQuery,AJAX,PHP数据交换问题


jQuery, AJAX, PHP data exchange issue

我尝试使用 jquery.ajax 函数将输入字段中的值发布到 php 文件中。php 部分必须将数据插入到 mysql 数据库中,生成一个唯一的 pincode 并将 json 的密码返回到 jquery 代码中。

但是在提交表格时没有任何反应...

当我直接进入浏览器中的主.php文件时,它向我显示一个唯一的密码,php 脚本甚至在数据库中插入密码。所以我认为 JSON 部分出错了,但我无法弄清楚原因。

我希望有人能告诉我我做错了什么。任何帮助都会太棒了!

代码

下面是工作代码!

网页部分:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>AJAX PHP JSON Test</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("form#userForm").submit(function() {
                var inputFname = $('#inputFname').attr('value');
                var inputLname = $('#inputLname').attr('value');
                $.ajax({
                    type: "POST",
                    url: "main.php",
                    data: {inputFname: inputFname,inputLname: inputLname},
                    dataType: "json",
                    contentType:"application/json; charset=utf-8",
                    success: function(data) {
                        $("p.succesText").html(data.jsCode);
                        $("form#userForm").hide();
                        $("div.success").fadeIn();
                    },
                    error: function(xhr, status, error) {
                        $("form#userForm").hide();
                        $("p.errorHead").html("Something went wrong.");
                        $("p.errorText").text("ResponseText: " + xhr.responseText
                                            + "Statuscode: " + xhr.status
                                            + "ReadyState: " + xhr.readyState);
                        $("div.error").fadeIn();
                    }
                });
                return false;
            });
        });     
    </script>
</head>
<body>
    <div class="MiddleWhite">
        <form id="userForm" method="post" name="userForm" action="">
        <label for="inputFname" class="LabelForInput">
            Enter your Forename
        </label>
        <input type="text" name="inputFname" id="inputFname" class="TextInput"
            size="20" />
        <br />
        <br />
        <label for="inputLname" class="LabelForInput">
            Enter your Surname
        </label>
        <input type="text" name="inputLname" id="inputLname" class="TextInput"
            size="20" />
        <br />
        <br />
        <br />
        <button type="submit" class="Button">
            Generate code</button>
        </form>
        <div class="success" style="display: none;">
            <p class="succesText">
            </p>
            <p class="checkCallText">
            </p>
        </div>
        <div class="error" style="display: none;">
            <p class="errorHead">
            </p>
            <p class="errorText">
            </p>
        </div>
    </div>
</body>
</html>

PHP部分:

<?php header('content-type: application/json; charset=utf-8');
    $log = array();

        $varFname = htmlspecialchars($_POST["inputFname"]);
        $varLname = htmlspecialchars($_POST["inputLname"]);
        //Make Database connection
        $db = mysql_connect("192.168.178.254","root","852456");
        if(!$db) die("Error connecting to MySQL database.");
        mysql_select_db("Ajax" ,$db);
        //Generate code and check if code already exists in the database
        do
        {
            $varCode = rand(10000, 99999);
            $dbCheckCode = "";
            $dbCheckCode = mysql_query("SELECT * FROM TableAjax WHERE code='$varCode'");
        }
        while (mysql_fetch_array($dbCheckCode) !== false);
        //Save the Form data in the database
        $sql = "INSERT INTO TableRecordcall (fname, lname, code) VALUES (".PrepSQL($varFname) . ", " .PrepSQL($varLname) . ", " .PrepSQL($varCode) . ")";
        mysql_query($sql);  
        //Return code to frontend
        $log['jsCode'] = $varCode;
        echo json_encode($log);

    //Clean SQL statement
    function PrepSQL($value)
    {
        if(get_magic_quotes_gpc()) 
        {
            $value = stripslashes($value);
        }
        $value = "'" . mysql_real_escape_string($value) . "'";
        return($value);
    }   
?> 

来自 JQuery API 这里

表单

及其子元素不应使用与表单属性(提交长度方法)冲突的输入名称或 ID。名称冲突可能会导致令人困惑的故障。有关规则的完整列表以及检查标记是否存在这些问题,请参阅 DOMLint。

你写的

<form id="submit" method="post" name="submit" action="">

尝试更改表单的 ID/名称。

你也没有使用

return false;

在峰会回调中,以防止默认表单提交。像这样更改您的 js 代码

$(document).ready(function() {
            $("form#submit").submit(function() {
                var inputFname = $('#inputFname').attr('value');
                var inputLname = $('#inputLname').attr('value');
                $.ajax({
                    type: "POST",
                    url: "main.php",
                    data: {inputFname: inputFname,inputLname: inputLname},
                    dataType: "json",
                    contentType:"application/json; charset=utf-8",
                    success: function(data) {
                        $("p.succesText").html(data.jsCode);
                        $("form#submit").hide();
                        $("div.success").fadeIn();
                    },
                    error: function(xhr, status, error) {
                        $("form#submit").hide();
                        $("p.errorHead").html("Something went wrong.");
                        $("p.errorText").text("ResponseText: " + xhr.responseText
                                            + "Statuscode: " + xhr.status
                                            + "ReadyState: " + xhr.readyState);
                        $("div.error").fadeIn();
                    }
                });
                return false;
            });
        });

在 $.ajax 中替换

data: {'inputFname': inputFname,'inputLname': inputLname},

data: {inputFname: inputFname,inputLname: inputLname},

希望对您有所帮助。