简体   繁体   English

用ajax更改html属性

[英]change html attributes with ajax

I have a html index document with a called "container" div tag, I load "login.php" into div tag through ajax statement in "indexScript.js". 我有一个带“容器” div标签的html索引文档,我通过“ indexScript.js”中的ajax语句将“ login.php”加载到div标签中。 I want load "successfulLogin.php" in the same tag if the "userNameBox" and "passBox" data is in the database table but if call the "validateLogin" method from the "action" attribute of "loginForm" the page is reloaded externally to index document and is displayed without navigation bar and without everything else. 如果数据库表中有“ userNameBox”和“ passBox”数据,我想在同一标签中加载“ successfulLogin.php”,但是如果从“ loginForm”的“ action”属性调用“ validateLogin”方法,则该页面将在外部重新加载索引文档,并且显示时没有导航栏,也没有其他所有内容。 Any idea ? 任何想法 ?

index.html: 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>

login.php: login.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: 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: 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: 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);
    }
}
?>

successfulLogin.htlm: successLogin.htlm:

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

The php is client-side and therefore is running as the page is compiling, where as the js is client-side, after page compiles. php是客户端的,因此在页面编译后正在运行,而js在客户端。 So this action="<?php validateLogin(); ?>" is coming back to either: 因此,该action="<?php validateLogin(); ?>"返回到以下任意一个:

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

or 要么

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

Neither of these I think are what you want and is likely why you are getting the page submit. 我认为这些都不是您想要的,也可能是您使页面提交的原因。 If you have errors on, you will find that the $_POST values will show as undefined in that function. 如果发生错误,您会发现$_POST值在该函数中显示为未定义。 You want to send both via ajax. 您想同时通过ajax发送。 I will show you using jQuery ajax (only because I know it better, but the principles are the same, which is the important part): 我将向您展示使用jQuery ajax(只是因为我更了解它,但是原理是相同的,这是重要的部分):

I am just adding the jquery library here: 我只是在这里添加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>

Now you need to have an engine to run ajax: 现在,您需要一个引擎来运行ajax:

/js/myscripts.js /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);
        });
    });
});

Now the dispatcher page will direct the ajax request. 现在,调度程序页面将指导ajax请求。 The dispatcher will write the response and the function in the success of the ajax call will place the contents of the write back into the container. 调度程序将写入响应,并且在成功执行ajax调用时,该函数会将写入的内容放回容器中。

/dispatcher.php /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>");
        }
}

I haven't tested this, but you should get the basic idea of it. 我没有测试过,但是您应该了解它的基本概念。

Your login/login.php will generate either <form action="<script> successfulLogin(); </script>" ...> or <form action="<script> failedLogin(); </script>" ...> . 您的login / login.php将生成<form action="<script> failedLogin(); </script>" ...> <form action="<script> successfulLogin(); </script>" ...><form action="<script> failedLogin(); </script>" ...> The "action" attribute in form tag is suppose to be a remote page not a js function, right? 表单标签中的“ action”属性应该是一个远程页面,而不是js函数,对吗?

You can either rebuild nav bar and everything again in php function validateLogin(), or call php function validateLogin() through another ajax method in your javascript and update the exiting page with the result accordingly. 您可以在php函数validateLogin()中重新构建导航栏和所有内容,或者通过JavaScript中的另一个ajax方法调用php函数validateLogin()并相应地更新结果页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM