简体   繁体   English

如何使用php动态验证html表单?

[英]How to validate the html forms dynamically using php?

I want to check the availability of a username (entered in an HTML input field) across my server database using php. 我想使用php在我的服务器数据库中检查用户名(在HTML输入字段中输入)的可用性。 I know we cannot do this unless we submit data to the server. 我知道除非将数据提交到服务器,否则我们将无法执行此操作。 One possible solution is to relaunch the page again but i don't want to do this. 一种可能的解决方案是再次重新启动页面,但是我不想这样做。 Is there any possiblity to do it alternatively? 是否有其他选择呢? How gmail does this? gmail如何? when we lose focus from the username field on signup form of gmail it automatically checks the availability. 当我们从gmail注册表单的用户名字段中失去焦点时,它会自动检查可用性。 Any ideas? 有任何想法吗?

Usually this is done using so-called "AJAX" technique. 通常,这是使用所谓的“ AJAX”技术完成的。 The idea is simple: you use javascript to send some data to your service, get some data back and update the page accordingly. 这个想法很简单:您可以使用javascript将一些数据发送到您的服务,获取一些数据并相应地更新页面。

Modern Javascript libraries have helper methods for this. 现代Javascript库为此提供了辅助方法

You should have a script on the server that accepts username, checks its availability and emits some JSON (or javascript, or whatever you are able to consume). 您应该在服务器上有一个脚本来接受用户名,检查其可用性并发出一些JSON(或javascript,或您可以使用的任何东西)。

You can also bind such check to onblur event. 您还可以将此类检查绑定到onblur事件。 jQuery has helper for this as well. jQuery也为此提供了帮助

So, in pseudocode it looks something like this 因此,在伪代码中看起来像这样

<script type='text/javascript'>
  jQuery(function() {
    $('#username_field').blur(function() {
      $.get('/check_availability.php', {username : this.val()}, function(data) {
        // update web page according to received data
      });
    });
  });
</script>

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

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