使用php将布尔值返回给ajax

时间:2017-12-26 14:06:07

标签: javascript php ajax database login

我现在还不太了解AJAX。我想知道,在用AJAX从JavaScript调用PHP文件之后,我是否可以返回一个布尔值。

更具体地说,我会解释我的代码。

我只在页面中登录了两步。首先,用户必须输入他的电子邮件地址。如果数据库中存在此密码,则用户必须输入其密码(不加载新页面)。然后,如果密码良好,他就已成功登录。

所以我在提交尚未编写的邮件时调用了一个函数(邮件是来自<input type="email" name="email" onsubmit="mailCheck(this.value)">的字符串):

function mailCheck(mail) {
    for (i = 0; i < mail.length; i++) {
        if (mail[i] == "") {
            document.getElementById("input").style.background = "#FFDDEE";
        }
    }
    if (!existing(mail)) {
        document.getElementById("input").style.background = "#FFDDEE";
    } else {
        //TODO: GO TO NEXT STEP (PASSWORD)
    }
}
function existing(mail) {
    var xmlhttp = new XMLHttpRequest();
    //TODO: USE mailCheck.php
    return false;
}

所以在这里,我专注于如何知道数据库中是否有邮件。所以我的文件mailCheck.php包含:

<?php
session_start();
$mail = htmlspecialchars($_POST['mail']);
$page = htmlspecialchars($_GET['reply']);

//Connect to the database (done)
//Ask the database (done)

//Act according to the answer of the database
if (!$result) {
       //TODO: RETURN FALSE WITH AJAX
} else {
       $_SESSION['ID'] = $result['ID'];
       //Others variables (done)
       $_SESSION['login'] = false;
       //TODO: RETURN TRUE WITH AJAX
}
?>

所以你知道我的函数如何存在(邮件)知道在mailCheck.php的过程中是否在数据库中找到了邮件?

非常感谢你的帮助。

巴斯蒂安

1 个答案:

答案 0 :(得分:0)

因为ajax本质上是异步的,所以你无法可靠地返回一个值 - 你可以使用围绕fetch意识形态构建的Promise api,它允许你返回一个值,或者你可以使用ajax回调以在邮件检查完成时根据服务器的响应继续处理。

使用fetch api,您可以将许多不同的请求链接在一起,因此如果依赖于先前的值为true或false等,您可以等待它在ajax中无法使用(除了使用回调和嵌套的ajax请求)

function mailCheck( mail ) {
    for( i = 0; i < mail.length; i++ ) {/* is this an array? */
        if ( mail[i] == "" ) document.getElementById("input").style.background = "#FFDDEE";
    }
    var _callback=function( response ){
        if( response===false ){
            document.getElementById("input").style.background = "#FFDDEE";
        } else {
            //TODO: GO TO NEXT STEP (PASSWORD)
        }
    }

    existing.call( this, mail, _callback );

}

function existing( mail, callback ) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange=function(){
        if( this.status==200 && this.readyState==4 )callback.call( this, this.response );
    }
    xhr.open('POST','mailcheck.php',true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send( 'mail='+mail );
}

使用fetch api的基本演示与ajax相比非常复杂,但最终在正确完成时更灵活。

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST') {
        ob_clean();

        $json=array('error');
        $_POST['time']=microtime();

        $dbhost =   'localhost';
        $dbuser =   'root'; 
        $dbpwd  =   'xxx'; 
        $dbname =   'xxx';
        $db =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );


        switch( $_POST['action'] ){
            case 'checkmail':
                /* db lookup and other tests */
                $email=filter_var( filter_input( INPUT_POST, 'email', FILTER_SANITIZE_EMAIL ), FILTER_VALIDATE_EMAIL );
                $status=false;

                $sql='select `username` from `users` where `email`=?';
                $stmt=$db->prepare( $sql );

                if( $stmt ){

                    $stmt->bind_param('s', $email );
                    $result = $stmt->execute();

                    if( $result ){
                        $stmt->store_result();
                        $stmt->bind_result( $username );
                        $stmt->fetch();
                        $stmt->close();
                        $db->close();

                        if( $username ) {
                            $_POST['username']=$username;
                            $status=true;
                        }
                    } else {
                        $status=false;
                    }
                } else {
                    $status=false;
                }

                $_POST['status']=$status;
            break;
            case 'login':
                /* validate user login */
                $email=filter_var( filter_input( INPUT_POST, 'email', FILTER_SANITIZE_EMAIL ), FILTER_VALIDATE_EMAIL );
                $password=filter_input( INPUT_POST, 'password', FILTER_SANITIZE_STRING );
                $status=false;

                $sql='select `username`,`token` from `users` where `email`=? and `password`=?';
                $stmt=$db->prepare( $sql );


                if( $stmt ){

                    $stmt->bind_param('ss', $email, $password );
                    $result = $stmt->execute();

                    if( $result ){
                        $stmt->store_result();
                        $stmt->bind_result( $username, $token );
                        $stmt->fetch();
                        $stmt->close();
                        $db->close();

                        if( $username ) {
                            $_POST['username']=$username;
                            $_POST['token']=$token;
                            $status=true;
                        }
                    } else {
                        $status=false;
                    }
                } else {
                    $status=false;
                }
                $_POST['status']=$status;
            break;
        }


        $json = json_encode( $_POST );

        header('Content-Type: application/json');
        header('HTTP/1.1 200 OK', true, 200 );
        exit( $json );
    }
?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8' />
        <title>Chained Fetch</title>

        <script>
            var options={
                once:false,
                capture:false,
                passive:false
            };

            document.addEventListener('DOMContentLoaded', function(){

                document.querySelector('form > input[type="button"]').onclick=function(event){

                    var stack=[];
                    var url=location.href;
                    var mail=document.querySelector('form > input[name="email"]');
                    var password=document.querySelector('form > input[name="password"]');

                    var _final=function(r){
                        alert( r );
                    }
                    var _isvalid=function( r ){
                        if( !r.status )throw new Error( r.action+' failed' );
                        return r.status;
                    }

                    /* the urls could be totally different php scripts */
                    stack.push({
                        url:url, /* checkmail.php */
                        config:{
                            method:'POST',
                            mode:'cors',
                            credentials:'include',
                            headers:{ 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8' },
                            body:'action=checkmail&email='+mail.value
                        }
                    });
                    stack.push({
                        url:url,/* login.php */
                        config:{
                            method:'POST',
                            mode:'cors',
                            credentials:'include',
                            headers:{ 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8' },
                            body:'action=login&password='+password.value+'&email='+mail.value
                        }
                    });





                    fetch( stack[0].url, stack[0].config )
                        .then( response => response.json() )
                        .then( data => _isvalid( data ) )
                        .then( data => fetch( stack[1].url, stack[1].config ) )
                        .then( response => response.json() )
                        .then( data => _isvalid( data ) )
                        .then( _final )
                        .catch( err => alert( err.message ) );

                }
            },options );
        </script>
    </head>
    <body>
        <form>
            <input type='email' name='email' />
            <input type='password' name='password' value='knickers' />
            <input type='button' value='Login' />
        </form>
    </body>
</html>