1

我用 php 和 javascript 创建了一个登录脚本。

我想要做的是登录用户而不刷新我迄今为止存档的页面,在 Stack Flow 用户的帮助下,我对 PHP 相当熟悉,但对 Javascript 客户端来说是新手。

无论如何,当用户输入正确的数据并且会话开始时,我如何让它调用淡出功能?

这是 PHP 方面

<?php
    require "../core/database.php";

    //lets create some veriables to use, This way is shorter
    $username = strip_tags(trim($_POST['user_login']));
    $password = strip_tags(trim($_POST['pass_login']));
    $md5_pass = md5($_POST['pass_login']);

    $user_login = mysql_real_escape_string($username);
    $pass_login = mysql_real_escape_string($md5_pass);

    if (($user_login) && ($password)) {
    //Connect to the database to fetch the users username and password
    $select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
    $user_rows = mysql_fetch_array($select_user);
    $username_row = $user_rows['username'];
    $password_row = $user_rows['password'];

        if(($username_row==$user_login)  && ($md5_pass==$password_row)) {
        //All user information is correct, Now start the session

        //I HAVE CALLED IT HERE HOPING THERE,S A BETTER WAY OF DOING THIS. IT WILL CAL
        echo "
        Yes, Now we can start the session right here, when your ready.

        <script> 
        $('#field').fadeOut();
        </script>";

        } else {

        echo "The username or password you entered is incorrect";
        }

    } else {
    echo "<b>Blank Fields</b> <br>
    You must enter A Username/Password Combination";
    }



?>

万一你需要它,有客户端aswill(被一些用户修改以使功能更好)

$(document).ready(function() {
    // Make a function that returns the data, then call it whenever you
    // need the current values
    function getData() {
        return {
            user_login: $('#user_login').val(),
            pass_login: $('#pass_login').val()

        }
    }


        function loading(e) {
        $('#content').html('Loading Data');
    }

    function check(e) {
        e.preventDefault();
        $.ajax({

            url: 'ajax/check.php',
            type: 'post',
            data: getData(), // get current values
            success: function (data) {
                $('#content').html(data);
            }
        });
    }

    // Don't repeat so much; use the same function for both handlers
    $('#field').keyup(function(e) {
        if (e.keyCode == 13) {
    var username = $('#user_login').val();

        loading(e);
        check(e);

        }
    });

    $('#submit').click(function(e) {
        if (e.keyCode != 13) {
        loading(e);
        check(e);
        } 


    });

});

由于 PHP 是服务器端,而 Java 脚本控制着客户端,可能最好的方法是这样做或调用它,但无论如何它都值得一问。


除此之外,一切都很顺利。

如果您愿意,您可以帮助更改加载数据的编码/工作方式,但是该功能运行良好,因此不需要太多。

4

3 回答 3

1

ajax 成功方法需要检查来自服务器的响应以查看登录是否成功,然后采取适当的操作:

// php    
if(($username_row==$user_login)  && ($md5_pass==$password_row)) {
            //All user information is correct, Now start the session

            echo 'correct';

            } else {

            echo 'The username or password you entered is incorrect';
            }

// js
function check(e) {
        e.preventDefault();
        $.ajax({
            url: 'ajax/check.php',
            type: 'post',
            data: getData(), // get current values
            success: function (data) {
                if (data === 'correct') {
                  $('#field').fadeOut();
                } else {
                  $('#content').html(data);
                }
            }
        });
    }
于 2013-05-30T12:28:54.453 回答
0

Returning JSON instead of raw HTML is much more flexible. Quick example:

PHP Side

<?php
require "../core/database.php";

$json = array('success' => false, 'error' => null);

$username = strip_tags(trim($_POST['user_login']));
$password = strip_tags(trim($_POST['pass_login']));
$md5_pass = md5($_POST['pass_login']);

$user_login = mysql_real_escape_string($username);
$pass_login = mysql_real_escape_string($md5_pass);

if (($user_login) && ($password)) {

    $select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
    $user_rows = mysql_fetch_array($select_user);
    $username_row = $user_rows['username'];
    $password_row = $user_rows['password'];

    if(($username_row==$user_login)  && ($md5_pass==$password_row)) {
        $json['success'] = true;
    } 
    else {
        $json['error'] = "The username or password you entered is incorrect";
    }

} else {
    $json['error'] = "<b>Blank Fields</b> <br>You must enter A Username/Password Combination";
}

echo json_encode($json);

Your AJAX function:

function check(e) {
    e.preventDefault();
    $.ajax({

        url: 'ajax/check.php',
        type: 'post',
        data: getData(), // get current values
        success: function (data) {
            var loginResult = JSON.parse(data);
            if(loginResult.success){

                //Login successful - fade out whatever form or fields
                //that you want to
                $('#field').fadeOut();

            } else{
                //Add error message to an error div or whatever
                $('#error').html(loginResult.error);
            }
        }
    });
}
于 2013-05-30T12:31:02.950 回答
0

我将首先说您的 PHP 应该为所有数据库查询使用更新的mysqli_*函数或PDO对象。此外,您应该使用准备好的语句来保护您免受 SQL 注入攻击。

另一件需要注意的事情是,在一个不会向浏览器输出任何内容的 PHP 文件中,或者换句话说,只是运行一些代码,您不需要结束标记。事实上,您不需要结束标签。这是因为结束标记之后的任何内容都会被发送到浏览器,这将包含在您的 AJAX 成功函数的响应中。这包括诸如空格和新行之类的东西。

现在,开始你的 PHP。您将要输出一些 JSON,以便您可以在 AJAX 中检查成功或失败。

PHP

<?php
    require "../core/database.php";

    //lets create some veriables to use, This way is shorter
    $username = strip_tags(trim($_POST['user_login']));
    $password = strip_tags(trim($_POST['pass_login']));
    $md5_pass = md5($_POST['pass_login']);

    $user_login = mysql_real_escape_string($username);
    $pass_login = mysql_real_escape_string($md5_pass);

    //Create an array to represent our JSON data.
    $json = array(
        "successCode" => 0
    );

    if (($user_login) && ($password)) {
        //Connect to the database to fetch the users username and password
        $select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
        $user_rows = mysql_fetch_array($select_user);
        $username_row = $user_rows['username'];
        $password_row = $user_rows['password'];

        if(($username_row==$user_login)  && ($md5_pass==$password_row)) {
            //All user information is correct, Now start the session
            //echo "Yes, Now we can start the session right here, when your ready."
            $json['successCode'] = 0;
        } else {
            //echo "The username or password you entered is incorrect";
            $json['successCode'] = 1;
        }

    } else {
        //echo "<b>Blank Fields</b> <br>
        //You must enter A Username/Password Combination";
        $json['successCode'] = 2;
    }

    //Set that our content type is JSON
    header("Content-type: application/json");
    echo json_encode($json); //Convert the PHP array to JSON and echo it as the response.

在我们的 PHP 中,我们创建了一个$json数组,它将记录successCode我们将响应客户端的内容。这将告诉客户端登录是成功还是失败,甚至发生了什么类型的失败。然后由客户端决定如何向用户显示成功或失败。这允许多个应用程序使用相同的服务器端源,但如果需要,会以不同的方式显示错误。

在 PHP 结束时,我们设置了标头Content-type以指定我们要发送回application/json客户端。然后,我们将 PHP 数组编码为 JSON,并将其输出到响应中。

jQuery/Javascript

//Let's define different messages depending on what status code we get on the client.
var errorMessages = [
    "Yes, Now we can start the session right here, when your ready.",
    "The username or password you entered is incorrect",
    "<b>Blank Fields</b><br />You must enter A Username/Password Combination"
];

function check(e) {
    e.preventDefault();
    $.ajax({
        url: 'ajax/check.php',
        type: 'post',
        data: getData(), // get current values
        success: function (data) {
            //First, make sure that data and data.successCode are defined.
            if (data && data.successCode) {
                //Here, you are getting back the JSON data from the login call.
                $('#content').html(errorMessages[data.successCode]);

                //If the successCode is 0, which means it was successful, then we want to fade out the #field div.
                if (data.successCode == 0) {
                    $('#field').fadeOut();
                }
            } else {
                //There must've been a server error. You'd handle that here.
            }
        }
    });
}

为什么将错误消息放在客户端而不是服务器上?因为它允许您轻松更改错误消息的显示方式,而无需触及服务器端代码。服务器只输出一个错误代码,客户端决定如何处理该代码。

Javascript 数组errorMessages定义了与其在数组中的索引相对应的错误消息。索引 0 处的错误消息将对应于successCode = 0,依此类推。如果您不打算使用顺序成功代码,则可以使用 javascript 对象来指定与每个错误代码对应的键。

于 2013-05-30T12:38:58.283 回答