如何使用servlet回复ajax帖子

时间:2016-08-24 21:50:35

标签: javascript jquery ajax servlets

我有一个用户名文本框,当用户输入一个名称时,它会获取该名称并发送到服务器,服务器检查用户名是否未被其他任何人使用,如果是,我需要发回一些数据并告诉客户端如果它不是我需要用户名已经取消我需要将文本框边框颜色变为绿色,现在我可以向服务器发送用户名值,但我不知道如何发送回来以及如何使用jquery接收发送的数据AJAX。

这是我的代码:

客户端:

$(document).ready(function() {
$('#Registeration_Username_box').on('input', function() {
    postUsernameToServer();
});

function postUsernameToServer() {
  var formData = {
            'username': $('input[name=UserName]').val(),
          };
          // process the form
     $.ajax({
         type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
         url: '../dusernameavailable', // the url where we want to POST
         data: formData, // our data object
         dataType: 'json', // what type of data do we expect back from the server
         encode: true
     }).done(function(data) {
         console.log(data);
     });
}
});

的servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String str = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
System.out.println(str);
}

2 个答案:

答案 0 :(得分:0)

successerror添加到您的ajax

function postUsernameToServer() {
var formData = {
  'username': $('input[name=UserName]').val(),
};
// process the form
$.ajax({
  type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
  url: '../dusernameavailable', // the url where we want to POST
  data: formData, // our data object
  dataType: 'json', // what type of data do we expect back from the server
  encode: true,
  success: function(data) {
    //TODO make the box green or whatever your requirement is
  },
  error: function() {
    //TODO username already taken
  }
});
}
});

在servlet中发送适当的响应。 您需要为ajax发送200以外的响应代码才能将其视为来自服务器的错误。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String str = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
    System.out.println(str);
    //TODO - check if user name exists or not
   if(user name already exists){
      response.setProperty(response.HTTP_STATUS_CODE, "500"); 
      PrintWriter out = response.getWriter();
      out.println("error");
      out.close();
   }
   else{
      PrintWriter out = response.getWriter();
      out.println("success");
      out.close();
   }

}     }

答案 1 :(得分:0)

为您的ajax调用添加成功处理程序。

你可以试试下面的东西;在哪里'绿色'和' red'是你在CSS文件中定义的css类。

$.ajax({
             type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
             url: '../dusernameavailable', // the url where we want to POST
             data: formData, // our data object
             dataType: 'json', // what type of data do we expect back from the server
             encode: true,
             success: function(response) {
               if(response.isUserNameAvailable == true) 
                    $('input[name=UserName]').addClass('green');
               else 
                   $('input[name=UserName]').addClass('red');
             }
         }).done(function(data) {
             console.log(data);
         });