2

我正在尝试使用 ajax 添加 div 以显示错误消息。但是我每次都得到 null 而不是正确的错误消息。空值是

<?php echo json_encode($_SESSION['msg']['login-err']); ?>;

我怎样才能解决这个问题?为什么显示为空?

JavaScript:

            $(document).ready(function(){
            $("#open").click(function(){
                $("#register").fadeIn(500);
            });
            $("#close").click(function(){
                $("#register").fadeOut(500);
            });
            $("#log").click(function(){
                username=$("#username").val();
                password=$("#password").val();
                submit=$("#log").val();
                $.ajax({
                    type: "POST",
                    url: "",
                    data: "submit="+submit+"&username="+username+"&password="+password,
                    success: function(html) {
                        if(html==true) {

                        }
                        else {
                            $("#error-log").remove();
                            var error_msg = <?php echo json_encode($_SESSION['msg']['login-err']); ?>;
                            $("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
                            <?php unset($_SESSION['msg']['login-err']); ?>
                        }
                    }
                });
                return false;
            });

成员.php:

<?php if(!defined('INCLUDE_CHECK')) header("Location: ../index.php"); ?>
<?php

require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined


session_name('Login');
// Starting the session

session_set_cookie_params(7*24*60*60);
// Making the cookie live for 1 week

session_start();

if($_SESSION['id'] && !isset($_COOKIE['FRCteam3482Remember']) && !$_SESSION['rememberMe'])
{
    // If you are logged in, but you don't have the FRCteam3482Remember cookie (browser restart)
    // and you have not checked the rememberMe checkbox:

    $_SESSION = array();
    session_destroy();

    // Destroy the session
}


if(isset($_GET['logoff']))
{
    $_SESSION = array();
    session_destroy();

    header("Location: ../../index.php");
    exit;
}

if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted

$err = array();
// Will hold our errors


if(!$_POST['username'] || !$_POST['password'])
    $err[] = 'All the fields must be filled in!';

if(!count($err))
{
    $_POST['username'] = mysql_real_escape_string($_POST['username']);
    $_POST['password'] = mysql_real_escape_string($_POST['password']);
    $_POST['rememberMe'] = (int)$_POST['rememberMe'];

    // Escaping all input data

    $row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));

    if($row['usr'])
    {
        // If everything is OK login

        $_SESSION['usr']=$row['usr'];
        $_SESSION['id'] = $row['id'];
        $_SESSION['rememberMe'] = $_POST['rememberMe'];

        // Store some data in the session

        setcookie('FRCteam3482Remember',$_POST['rememberMe']);
    }
    else $err[]='Wrong username and/or password!';
}

if($err) {
    $_SESSION['msg']['login-err'] = implode('<br />',$err);
    // Save the error messages in the session

    header("Location: index.php");
}
else
    header("Location: workspace/index.php");
    echo 'true';
exit;
}
4

2 回答 2

1

通常,AJAX 请求向 PHP 页面发出请求,该页面返回一个值。它通常是 JSON,但不一定是。这是一个例子。

$.ajax({
    type: "POST",
    url: "a request URL",
    data:{
        'POST1':var1,
        'POST2':var2
        }
    success: function(result)
        {
        //Do something based on result. If result is empty. You have a problem.
        }
});

您的 PHP 页面并不总是返回值,因此很难知道发生了什么。您的解决方法是在您的页面返回空时使用 javascript 变量来保存回显的 PHP 数据。但这不适用于您的情况。将 PHP 变量回显到 javascript 中有时可能会很好,但这不是一个好的做法。

它不适用于您的情况,因为您的 javascript 变量是在首次加载页面时设置的。此时变量$_SESSION['msg']['login-err']尚未设置(或可能包含一些不相关的数据),这也是您的 javascript 变量也将包含的内容。

当您按照我提到的方式进行操作时,您还可以使用console.log(result)或之类的函数alert(result)来手动查看 PHP 页面的结果并修复任何问题。

我建议做类似以下的事情。

if($err) {
    $_SESSION['msg']['login-err'] = implode('<br />',$err);
    echo $_SESSION['msg']['login-err'];
}
else
    echo 'success';
}

Javascript

$.ajax({
        type: "POST",
        url: "",
        data: "submit="+submit+"&username="+username+"&password="+password,
        success: function(response) {
            if(response=='success') {
                alert("Woo! everything went well.  What happens now?");
                //do some stuff
            }
            else {
                alert("oh no, looks like we ran into some problems.  Response is"+ response);
                $("#error-log").remove();
                var error_msg = response;
                $("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
            }
        }
});

这可能不一定完全按照您的预期工作,但对您来说是一个良好的开端。

于 2013-03-12T05:43:07.150 回答
0

通过查看代码,您似乎是先进行重定向,然后再发送响应。

下面的代码片段有问题

if($err) {
    $_SESSION['msg']['login-err'] = implode('<br />',$err);
    // Save the error messages in the session

    header("Location: index.php");
}
else
    header("Location: workspace/index.php");
    echo 'true';
exit;
}
于 2013-03-12T06:37:40.117 回答