【问题标题】:change html attributes with ajax用ajax改变html属性
【发布时间】:2018-02-04 00:55:06
【问题描述】:

我有一个名为“container”的 div 标签的 html 索引文档,我通过“indexScript.js”中的 ajax 语句将“login.php”加载到 div 标签中。如果“userNameBox”和“passBox”数据在数据库表中,我想在同一标记中加载“successfulLogin.php”,但如果从“loginForm”的“action”属性调用“validateLogin”方法,则在外部重新加载页面索引文档并在没有导航栏和其他所有内容的情况下显示。有什么想法吗?

index.html:

<head>
    <title>English Site</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="styles/layout.css" type="text/css">
    <script src="indexScript.js"></script>
</head>
<nav><!--Barra de navegacion...!-->
    <ul>
        <li><a id="loginLink">Iniciar sesión</a></li>
        <li><a id="registerLink">Registro</a></li>
        <li><a href="#">Estudiantes</a></li>
        <li><a href="#">Docentes</a></li>
        <li><a href="#">Contenido</a></li>
        <li><a href="#">Diccionario</a></li>
    </ul>
</nav>  
<div id="container">
    <!--Container content-->
</div>

登录.php:

 <html>
<?php include_once("validateLogin.php"); ?>
    <body>
        <h3>Formulario de ingreso...!</h3>
        <form action="<?php validateLogin(); ?>" onSubmit="return(validateLoginForm());" method="post" id="loginForm" name="loginForm">
            <table>
                <tr>
                    <td><p id="failedLoginLabel" style="color: #B5090B; font-style: italic; font-size: 16px; visibility: hidden;">El nombre de usuario o la contraseña son incorrectos...!</p></td>
                </tr>
                <tr>
                    <td><input type="text" id="userNameBox" name="userNameBox" value="Nombre de usuario" onFocus="this.value=(this.value=='Nombre de usuario')? '' : this.value ;" onBlur="this.value=(this.value=='')? 'Nombre de usuario' : this.value ;" style="width: 70%;"></td>
                </tr>
                <tr>
                    <td><input type="password" id="passBox" name="passBox" value="Contraseña" onFocus="this.value=(this.value=='Contraseña')? '' : this.value ;" onBlur="this.value=(this.value=='')? 'Contraseña' : this.value ;" style="width: 70%;"></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Login" style="width: 71%; height: 30px;"></td>
                </tr>
            </table>
        </form>
    </body>

indexScript.js:

window.addEventListener("load", load, false);

var registerLink, loginLink, container;

function load(){
    container               = document.getElementById("container");
    registerLink            = document.getElementById("registerLink");
    loginLink               = document.getElementById("loginLink");

    registerLink.addEventListener("click", showRegisterForm, false);
    loginLink.addEventListener("click", showLoginForm, false);
} 
function showLoginForm(){
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState == 4 && request.status == 200) {
            container.innerHTML = request.responseText;
        }
    };
    request.open("POST", "login/login.php", true);
    request.send();
}

function validateLoginForm(){
    var validation              = true;
    var userName                = document.loginForm.userNameBox;
    var pass                        = document.loginForm.passBox;
    var failedLoginLabel        = document.getElementById("failedLoginLabel");
    if(userName.value == "Nombre de usuario" || pass.value == "Contraseña"){
        failedLoginLabel.style.visibility = "visible";
        validation = false;
    }else{
        failedLoginLabel.style.visibility = "hidden";
    }
    return validation;
}

validateLogin.php:

<?php
function validateLogin(){
    $userName = $_POST["userNameBox"];
    $password = $_POST["passBox"];
    require_once("../connection/connection.php");
    $connection = Connection::getConnection();
    $query = "select * from english_students_table where user=:userNameMarker";
    $result = $connection->prepare($query);
    $success = $result->execute(array(":userNameMarker" => $userName));
    $register = $result->fetch(PDO::FETCH_ASSOC);

    if($success && password_verify($password, $register["password"])){
        session_start(); /* Crea una sesión o reanuda la actual basada en un identificador de sesión pasado mediante una petición GET o POST, o mediante una cookie.*/
        $_SESSION["userSession"] = $_POST["userNameBox"];
        echo("<script> successfulLogin(); </script>");
    }else{
        echo("<script> failedLogin(); </script>");
    }
}
?>

connection.php:

<?php
class Connection{
    public static function getConnection(){
        $dbHost = "localhost";
        $dbName = "test_database";
        $dbUser = "root";
        $dbPassword = "";
        $connection = new PDO("mysql:dbname=$dbName; host=$dbHost", $dbUser, $dbPassword);
        $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return($connection);
    }
}
?>

成功登录.htlm:

<!doctype html>
<html>
    <body>
        <h2>Login exitoso...!</h2>
    </body>
</html>

【问题讨论】:

    标签: javascript php html ajax validation


    【解决方案1】:

    php是客户端,因此在页面编译时运行,而js是客户端,在页面编译后。所以这个action="&lt;?php validateLogin(); ?&gt;" 又回到了:

    <form action="<script> successfulLogin(); </script>"
    

    <form action="<script> failedLogin(); </script>"
    

    我认为这些都不是您想要的,并且可能是您提交页面的原因。如果您有错误,您会发现$_POST 值将在该函数中显示为未定义。您想通过 ajax 发送两者。我将向您展示使用jQuery ajax(只是因为我更了解它,但原理相同,这是重要的部分):

    我只是在这里添加jquery库:

    <head>
        <title>English Site</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="styles/layout.css" type="text/css">
        <script src="indexScript.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="indexScript.js"></script>
    </head>
    <nav><!--Barra de navegacion...!-->
        <ul>
            <li><a id="loginLink">Iniciar sesión</a></li>
            <li><a id="registerLink">Registro</a></li>
            <li><a href="#">Estudiantes</a></li>
            <li><a href="#">Docentes</a></li>
            <li><a href="#">Contenido</a></li>
            <li><a href="#">Diccionario</a></li>
        </ul>
    </nav>  
    <div id="container">
        <!--Container content-->
    </div>
    

    现在你需要一个引擎来运行 ajax:

    /js/myscripts.js

    // Create a custom re-useable ajax function
    var MyAjaxEngine = function($)
    {
        var self = this;
        this.ajax = function(data,func)
        {
            $.ajax({
                // This page will observe your ajax and decide what to do based
                // on the actions you send
                'url': '/dispatcher.php',
                'type': 'post',
                'data': data,
                'success': function(response) {
                    // Run your function here
                    func(response);
                }
            });
    
            return self;
        };
    }
    
    // Document ready    
    $(function(){
        // Create ajax instance
        var Remote = new MyAjaxEngine($);
        // Run the ajax right from the start
        // send login_form action 
        Remote.ajax({"action":"login_form"},function(response){
            // Write hrml to the container
            $("#container").html(response);
        });
        // Listen for the form submission
        $(this).on('submit','#loginForm',function(e){
            // Stop submission
            e.preventDefault();
            // Create ajax call
            Remote.ajax({
                // This time send a login action
                "action":"login",
                // Send the form data in an array
                "form":$(this).serializeArray()
            },function(response){
                #write array back
                $("#container").html(response);
            });
        });
    });
    

    现在调度程序页面将引导 ajax 请求。调度程序将写入响应,ajax 调用成功的函数会将写入的内容放回容器中。

    /dispatcher.php

    <?php
    # Just start session always
    session_start();
    # Don't even go on if there are no actions to compute
    if(empty($_POST['action']))
        die('Request was empty.');
    # Get database
    include_once(__DIR__.'/connection/connection.php');
    # Decide on actions
    switch($_POST['action']) {
        case('login_form'):
            # Write back just the login form
            include(__DIR__.'/login.php');
            exit;
        case('login'):
            $form = $_POST['form'];
            $userName = $form["userNameBox"];
            $password = $form["passBox"];
            $connection = Connection::getConnection();
            $result = $connection->prepare("select * from english_students_table where user=:userNameMarker");
            $success = $result->execute(array(":userNameMarker" => $userName));
            $register = $result->fetch(PDO::FETCH_ASSOC);
    
            if($success && password_verify($password, $register["password"])){
                $_SESSION["userSession"] = $form["userNameBox"];
                die("<script> successfulLogin(); </script>");
            }else{
                die("<script> failedLogin(); </script>");
            }
    }
    

    我没有测试过,但你应该了解它的基本概念。

    【讨论】:

      【解决方案2】:

      您的 login/login.php 将生成 &lt;form action="&lt;script&gt; successfulLogin(); &lt;/script&gt;" ...&gt;&lt;form action="&lt;script&gt; failedLogin(); &lt;/script&gt;" ...&gt;。 form标签中的“action”属性应该是远程页面而不是js函数吧?

      您可以在 php 函数 validateLogin() 中重新构建导航栏和所有内容,或者通过 javascript 中的另一个 ajax 方法调用 php 函数 validateLogin() 并相应地使用结果更新退出页面。

      【讨论】:

      • 我认为您几乎完全按照我在回答中所写的内容进行了说明。您的回答对已经陈述/证明的内容有何改进?
      • 如果我理解正确,您希望在调用 validateLogin 后显示导航栏和其他所有内容,对吗?
      猜你喜欢
      • 1970-01-01
      • 2016-07-30
      • 2014-12-03
      • 2020-10-27
      • 1970-01-01
      • 2021-11-24
      • 2015-09-22
      • 1970-01-01
      • 2015-06-09
      相关资源
      最近更新 更多