简体   繁体   English

将Ajax发送到控制器

[英]Sending Ajax to controller

I am trying to get live validation on a register form that tells the user if the username they are trying has already been taken or not. 我正在尝试在注册表单上进行实时验证,该表单告诉用户他们尝试使用的用户名是否已被使用。 I am using jQuery to detect change in the input and want to send the username they type as an AJAX to a Spring controller I have set up. 我正在使用jQuery来检测输入中的更改,并想将它们作为AJAX输入的用户名发送给我设置的Spring控制器。 Eventually it will plug it into a query and return if that username has already been registered. 最终,它将把它插入查询中,并返回该用户名是否已注册。 I am having trouble with the AJAX. 我在使用AJAX时遇到麻烦。 Any ideas on how to accurately send the request? 关于如何准确发送请求的任何想法?

My AJAX: 我的AJAX:

$(document).ready(() => {
    function checkPassword() {
        let usernameGiven = $("#username").val();
        $.post( "/check",
            {username: usernameGiven} ,
            function(data) {
            console.log(data)
        })

    }

    $('#username').on('input', () => {
        checkPassword()
    });

});

My Controller: 我的控制器:

 @PostMapping("/check")
public String checkUsername(@RequestParam(name = "username") String username){

}

I haven't used jQuery in a long time but I don't think you can pass data with your post using that syntax. 我已经很久没有使用jQuery了,但我认为您无法使用该语法在您的帖子中传递数据。 Try: 尝试:

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

dataType is the type of data you expect back from the server (xml, json, script, text, html). dataType是您希望从服务器返回的数据类型(xml,json,脚本,文本,html)。

While you're testing this, make sure you're actually returning some data back from your controller too, even if it's just mock data for now. 在测试时,请确保实际上也从控制器返回了一些数据,即使目前只是模拟数据。

Maybe can work if you use: 如果使用,也许可以工作:

<input id="username" onBlur="checkIfUserExist()">

Make a javascript function: 制作javascript函数:

function checkIfUserExist() {

     $.ajax({
          url: "/check",
          data:'username='+$("#username").val(),
          type: "POST",
          success:function(data){
          console.log(data); //content user availability status
     },
     error:function (){}
     });
   }
 }

Think I found what I was looking for. 想想我找到了我想要的东西。 This is working for me. 这对我有用。 Let me know if you think there is a more efficient way of doing this. 如果您认为有更有效的方法可以告诉我。

@RestController
 public class TestController {

     @GetMapping("/getString")
      public String getString(@RequestParam(name = "username") String username) {

          return JSONObject.quote(username);
      }
 }

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

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