简体   繁体   English

服务器端验证,客户端通知?

[英]Server-side validation, client-side notification?

When a user fills a login form with an username and a password I use php to do a server-side validation of the data inputted by comparing it with the one in the "users" table in the SQL database. 当用户使用用户名和密码填写登录表单时,我使用php通过将数据与SQL数据库中“users”表中的数据进行比较,对输入的数据进行服务器端验证。 I'd like to notify the user if the password is incorrect without redirecting him - using a javascript dialog, for instance. 我想在没有重定向的情况下通知用户密码是否正确 - 例如,使用javascript对话框。 Is that possible? 那可能吗? The only way I found to notify the user was: 我发现通知用户的唯一方法是:

if ($password_given != $password_from_db) {
    echo "Wrong password."; // Dull non-html notification issued by the server
};

or 要么

if ($password_given != $password_from_db) {
    header('Location: index.php?page=wrongpassword'); //Need redirection
};

Is there anyway to this differently? 这有什么不同吗?

A javascript to get the inputted data, send it to the server to be processed is an idea, but how could I return a result for the javascript to use? 获取输入数据的javascript,将其发送到服务器进行处理是一个想法,但我怎样才能返回javascript使用的结果?

Can be done using AJAX - 可以使用AJAX完成 -

<form onsubmit="return ajaxsubmit();">
...
</form>

Javascript- Javascript成为

function ajaxsubmit() {
    param = 'email=' + document.forms.login.email + '&' + 'pass=' + document.forms.login.pass;
    xhr = new XMLHttpRequest();
    xhr.open('POST', 'process.php', true);
    xhr.onload = function() {
        if(xhr.responseText.indexOf("Wrong")>=0) {
            //wrong password, ask user to try again
        } else {
            //correct password, redirect or do stuff.
        }
    };
    xhr.setRequestHeader('Content-type: application/x-www-form-urlencoded'); 
    xhr.send(param);
    return false;
}

You can keep your server-side validation code in process.php and use the above code in the page where the form is. 您可以将您的服务器端验证代码保存在process.php中,并在表单所在的页面中使用上述代码。 You're done. 你完成了。

JQuery JQuery的

$.post("test.php", $("#testform").serialize())
.done(function(data) {
  if( data=='validated')
window.location.href = "successpage.php";
else
 alert ('password dont match!');

});

php PHP

if ($password_given != $password_from_db) 
    echo "notvalidated."; 
else
   echo     echo "validated.";

您可以对服务器进行Ajax调用,并允许用户根据服务器返回的结果登录或显示错误消息。

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

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