简体   繁体   English

如何使javascript响应php事件?

[英]How to make javascript work as a response to php events?

I am developing a website for practice, and I would like to know how to use JS to notify the user that the username he picked is already in use, all works fine, if my function(check_username) returns false, the user succesfully registers himself into the site, otherwise the register won't happen. 我正在开发一个练习网站,我想知道如何使用JS通知用户他选择的用户名已在使用中,一切正常,如果我的函数(check_username)返回false,则用户成功注册了自己进入网站,否则注册不会发生。

When the user can't register I would like to know how can I notify the user with a js script. 当用户无法注册时,我想知道如何使用js脚本通知用户。

<?php 
    //database includes
    include_once('../config/init.php');
    include_once('../database/users.php');

    if(!check_username($_POST['username'])) {
        insertUser($_POST['name'], $_POST['username'], $_POST['email'], $_POST['pass']);
    }
    else header('Location: ../index.php');
?>

One way would be to change your redirect on failure to a javascript message 一种方法是将失败时的重定向更改为javascript消息

else
{
  echo "<script>alert('Username already exists');</script>";
}

That's a very trivial example to get you started since you mentioned you're learning JS. 这是一个非常简单的示例,因为您提到要学习JS,因此可以帮助您入门。 You can build a lot of improvements on that. 您可以在此基础上进行很多改进。

You can set the returns into a javascript variable and use it to display message if the user is not registered. 您可以将返回值设置为javascript变量,如果用户未注册,则可以使用它显示消息。

var x = <?php echo check_username($_POST['username']); ?>;
if(x) {
    alert("You are not registered");
}

You can use php ajax for a live notification to users. 您可以使用php ajax向用户实时通知。

 <script> $(document).ready(function() { $("#InputFieldID").keyup(function (e) { //removes spaces from username $(this).val($(this).val().replace(/\\s/g, '')); //Getting value of input field. var username = $(this).val(); //Check only if the username characters are above 4 if(username.length >= 4){ $("#IndicatorDivID").html('<p style="color:#ffbf25;">Checking..!</p>'); $.ajax({ type: 'POST', url: 'check_username.php', data: {"username": username}, dataType: 'json', success: function (data) { if(data.response=='true') alert("Already Exist"); } }); } }); }); //Username Checker </script> 

The result fo check_username.php must be in json format. check_username.php的结果必须为json格式。 eg: {"response":"false"} 例如:{“ response”:“ false”}

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

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