Return 布尔值 php 到 ajax

Return boolean with php to ajax

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

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

我正在仅在页面中进行两步登录。所以首先,用户必须输入他的电子邮件地址。如果这个存在于数据库中,用户必须输入他的密码(无需加载新页面)。那么如果密码没问题,他就成功登录了。

所以我在提交尚未写的邮件时调用了一个函数(邮件是来自<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
}
?>

那么你知道我的existing(mail)函数在mailCheck.php的处理过程中是如何知道邮件是否在数据库中找到的吗?

非常感谢您的帮助。

巴斯蒂安

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

使用 fetch api 您可以将许多不同的请求链接在一起,因此如果依赖于先前的值是真还是假等,您可以等待它可用,而您不能在 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>