在 GRAILS 中使用 ajax 检查用户名可用性

发布于 2024-07-13 23:43:58 字数 518 浏览 8 评论 0原文

我正在 grails 中做一个 Web 应用程序。现在我正在制作注册页面。在注册页面中,我想通过 ajax 检查用户名可用性。我可以编写在控制器或服务中检查用户名可用性的代码。我对如何联系服务器感到震惊从客户端通过ajax。

我的示例 gsp 代码

<g:form method="post" action="signup" controller="auth">
 <input type="text" name="name" >
 <input type="text" name="username" >
 <input type="password" name="password" >
 <input type="submit" value="signup">
 </g:form>

在上面的代码中,如果用户名文本框失去焦点,它应该检查可用性。我做了一些谷歌搜索。但我无法得到我想要的东西。任何人都可以为此提供帮助或好的教程吗?

谢谢。

I am doing one web application in grails.Now I am making signup page.In signup page I want to check the username availability via ajax.I can write the code for username availability checking in controller or service.I struck with how to contact server from client side via ajax.

My sample gsp code is

<g:form method="post" action="signup" controller="auth">
 <input type="text" name="name" >
 <input type="text" name="username" >
 <input type="password" name="password" >
 <input type="submit" value="signup">
 </g:form>

In the above code if the username textbox lost the focus it should check for availabity.I did a bit of google search.But i couldn't get what i want.Can anyone provide help or good tutorial for this?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

大海や 2024-07-20 23:43:59

Grails 有一些很棒的内置 ajax 标签,但我更喜欢直接使用 javascript 库(即 jquery)...

  1. 下载 jquery< /a> 并复制到 web-app/js/jquery.js

  2. 在表单 gsp 或布局的 head 部分添加:

  3. 在您的表单 gsp 中,我建议在用户名的输入字段中添加 id 属性,这样可以更轻松地通过 id 引用元素:

  4. 在您的控制器方法中,您可以检查您的域/服务/等以查看名称是否免费。 下面是一个人为的示例,它以 JSON 形式返回响应,但您也可以返回 html 来填充 div,这取决于您想要如何提醒用户。

<代码>

    class UserController {
      def checkAvailable = {
        def available
        if( User.findByUsername(params.id) ) {
           available = false
        } else {
           available = true
        }
        response.contentType = "application/json"
        render """{"available":${available}}"""
    }

5、在表单 gsp 的 head 部分添加

    <script type="text/javascript">
    // wait for dom to load
    $(function(){
      // set onblur event handler
      $("#username").blur(function(){
        // if some username was entered - this == #username
        if($(this).length > 0) {
          // use create link so we don't have to hardcode context
          var url = "${createLink(controller:'user', action:'checkAvailable')}"
          // async ajax request pass username entered as id parameter
          $.getJSON(url, {id:$(this).val()}, function(json){
            if(!json.available) {
              // highlight field so user knows there's a problem
              $("#username").css("border", "1px solid red");
              // maybe throw up an alert box
              alert("This username is taken");
              // populate a hidden div on page and fill and display it..
              $("#somehiddendiv").html("This ID is already taken").show();
            }
          });
        }
      });
    });
    </script>

当然有很多方法可以实现这一点,我只是更喜欢 jquery 而不是使用一些内置的 ajaxy 功能。

Grails has some great built in ajax tags, but I prefer to use a javascript library directly (namely jquery)...

  1. Download jquery and copy to web-app/js/jquery.js

  2. In the head section of your form gsp or your layout add:

    <g:javascript src="jquery.js"/>

  3. In your form gsp I'd recommend adding an id attribute to your input field for username, makes it easier to reference an element by id:

    <input type="text" name="username" id="username" value=""/>

  4. In your controller method you can check your domain/service/etc to see if name is free. Below is a contrived example that returns the response as JSON, but you could also return html to fill a div, just depends on how you want to alert the user.

    class UserController {
      def checkAvailable = {
        def available
        if( User.findByUsername(params.id) ) {
           available = false
        } else {
           available = true
        }
        response.contentType = "application/json"
        render """{"available":${available}}"""
    }

5, In your form gsp in the head section add

    <script type="text/javascript">
    // wait for dom to load
    $(function(){
      // set onblur event handler
      $("#username").blur(function(){
        // if some username was entered - this == #username
        if($(this).length > 0) {
          // use create link so we don't have to hardcode context
          var url = "${createLink(controller:'user', action:'checkAvailable')}"
          // async ajax request pass username entered as id parameter
          $.getJSON(url, {id:$(this).val()}, function(json){
            if(!json.available) {
              // highlight field so user knows there's a problem
              $("#username").css("border", "1px solid red");
              // maybe throw up an alert box
              alert("This username is taken");
              // populate a hidden div on page and fill and display it..
              $("#somehiddendiv").html("This ID is already taken").show();
            }
          });
        }
      });
    });
    </script>

Of course there are many ways to implement this, I just happen to prefer jquery over using some of the built-in ajaxy features.

岁吢 2024-07-20 23:43:59

通过使用 remoteFunction 方法我们可以做到这一点。

By using remoteFunction method we can do that.

°如果伤别离去 2024-07-20 23:43:59

您首先需要将一些事件绑定到用户名的输入框 - 我建议使用 JS 库,如 jQuery、mootools 或任何其他高质量库。

绑定一个事件,比如onblur,到输入框,你可以编写一个函数来发出< a href="http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback" rel="nofollow noreferrer">向您的服务器发送 http GET 请求(例如,/register/checkAvailability?username= 此处的用户名),响应将显示在某处(可能在输入框旁边)。

you will first need to bind some event to the input box for username - i recommend using a JS library like jQuery, or mootools, or any of the other high quality library out there.

binding an event, like onblur, to the input box, you can write a function which issue a http GET request to your server (e.g., /register/checkAvailability?username=the username here), and the response will be displayed somewhere (may be next to the input box).

嘦怹 2024-07-20 23:43:59

通过这些更改开箱即用。

$("#username").bind("change paste keyup", function() {
 $(function(){
        // set onblur event handler
        $("#username").bind("change paste keyup", function() { /*<<<<< !UPDATE THIS LINE!******/
            // if some username was entered - this == #username
            if($(this).length > 0) {
                // use create link so we don't have to hardcode context
                var url = "${createLink(controller:'user', action:'checkAvailable')}"
                // async ajax request pass username entered as id parameter
                $.getJSON( url, { id:$(this).val() }, function(json){
                    if(!json.available) {
                          // highlight field so user knows there's a problem
                          $("#username").css("border", "1px solid red");
                          // maybe throw up an alert box
                          alert("This username is taken");
                          // populate a hidden div on page and fill and display it..
                          $("#somehiddendiv").html("This ID is already taken").show();
                    }
                });
            }
        });
    });

Working out of the box with theses changes.

$("#username").bind("change paste keyup", function() {
 $(function(){
        // set onblur event handler
        $("#username").bind("change paste keyup", function() { /*<<<<< !UPDATE THIS LINE!******/
            // if some username was entered - this == #username
            if($(this).length > 0) {
                // use create link so we don't have to hardcode context
                var url = "${createLink(controller:'user', action:'checkAvailable')}"
                // async ajax request pass username entered as id parameter
                $.getJSON( url, { id:$(this).val() }, function(json){
                    if(!json.available) {
                          // highlight field so user knows there's a problem
                          $("#username").css("border", "1px solid red");
                          // maybe throw up an alert box
                          alert("This username is taken");
                          // populate a hidden div on page and fill and display it..
                          $("#somehiddendiv").html("This ID is already taken").show();
                    }
                });
            }
        });
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文