Use jQuery ajax() method to submit asynchronously and verify user login

The authentication of user login can be submitted using form form, or it can be submitted asynchronously using ajax technology.

AJAX, Asynchronous Javascript And XML, is a technology for creating fast dynamic web pages.
AJAX enables web pages to be updated asynchronously by exchanging a small amount of data with the server in the background.

This means that a part of the page can be updated without reloading the entire page.
Traditional web pages (without AJAX) need to reload the entire web page if they need to update the content.

The jQuery ajax() method is the underlying AJAX implementation of jQuery.

The ajax() method has several important parameters:

  $.ajax({
        url: "detail.html",  //Address of sending request, parameter of String type
        data:{id:"id"},      //If the data sent to the server, Object or String type parameter, is no longer a String, it will be automatically converted to String format.
        type: "POST",        //Request method, default to GET, String type parameter
        dataType:'json',     //Expected data type returned by the server, parameter of String type; available types are (xml, html, json, json, text)
        timeout:1000,        //Request timeout, MS
        async: true,         // The default is true, all requests are asynchronous, and Boolean type parameters
        beforeSend: function(XMLHttpRequest){  //Functions invoked before sending requests

        },
        complete: function(XMLHttpRequest, textStatus){  //Callback function called after the request is completed (called by success or failure).

        },

        success:function(){  //Callback function called after successful request

        },
        error:function(){  //Function called when the request fails

        }
  });

Example:

Verify user login foreground code

$("#loginBtn").click(function(){
    var user = new Object();
    user.loginCode = $.trim($("#loginCode").val());
    user.password = $.trim($("#password").val());

    //Non empty verification of foreground
    if(user.loginCode == "" || user.loginCode == null){
        $("#loginCode").focus;
        $("#formtip").css("color","red");
        $("#formtip").html("Sorry, the login account cannot be empty.");
    }else if(user.password == "" || user.password == null){
        $("#password").focus;
        $("#formtip").css("color","red");
        $("#formtip").html("Sorry, the login password cannot be empty.");
    }else{
        $("#formtip").html("");
        //If the account and password are not empty, the ajax asynchronous submission is performed
        $.ajax({
            type:'POST',  //The submission method is POST
            url:'/login.html', //Requested path
            data:{user:JSON.stringify(user)}, //Pass user to the background as a JSON string
            dataType:'html', //The data type returned in the background is html text
            timeout:1000,  //Request timeout, MS
            error:function(){  //Callback method for request failure
                $("#formtip").css("color","red");
                $("#formtip").html("Login failed! Please try again.");
            },
            success:function(result){   //Callback method for successful request
                if(result != "" && result == "success"){
                //If login succeeds, go to "/ main.html"
                    window.location.href='/main.html';
                }else if(result == "failed"){
                    $("#formtip").css("color","red");
                    $("#formtip").html("Login failed! Please try again.");
                    $("#loginCode").val('');
                    $("#password").val('');
                }else if(result == "nologincode"){
                    $("#formtip").css("color","red");
                    $("#formtip").html("Login account does not exist! Please try again.");
                }else if(result == "pwderror"){
                    $("#formtip").css("color","red");
                    $("#formtip").html("Login password error! Please try again.");
                }else if("nodata" == result){
                    $("#formtip").css("color","red");
                    $("#formtip").html("Sorry, there is no data to process! Please try again.");
                }
            }
        });
    }
});

Verify user login background code

    /*@responseBody The function of annotation is to write the object returned by the controller's method to the body area of the response object after it is converted to the specified format through an appropriate converter, which is usually used to return JSON data or XML Data, it should be noted that after using this annotation, the view processor will not walk any more, but directly write the data into the input stream, whose effect is equivalent to outputting the data in the specified format through the response object.*/
    @RequestMapping("/login.html")
    @ResponseBody
    public Object login(HttpSession session,@RequestParam String user){

    //Background non empty verification
        if(user == null || "".equals(user)){
            return "nodata";
        }else{

        //Convert user to json object and then to java object
            JSONObject userObject = JSONObject.fromObject(user);
            User userObj= (User)userObject.toBean(userObject, User.class);

            try {
                if(userService.loginCodeIsExit(userObj) == 0){//This login account does not exist
                    return "nologincode";
                }else{
                    User _user = userService.getLoginUser(userObj);

                    //Login successfully
                    if(null != _user){
                        //Current user saved to session
                        session.setAttribute(Constants.SESSION_USER, _user);

                        //Update lastLoginTime of current user login
                        User updateLoginTimeUser = new User();
                        updateLoginTimeUser.setId(_user.getId());
                        updateLoginTimeUser.setLastLoginTime(new Date());
                        userService.modifyUser(updateLoginTimeUser);
                        updateLoginTimeUser = null;
                        return "success";
                    }else{
                      //Password error
                        return "pwderror";
                    }
                }
            } catch (Exception e) {
                return "failed";
            }
        }
    }

For more detailed parameters and usage of ajax() method, see w3cschool manual

Tags: JSON xml Session JQuery

Posted on Mon, 30 Mar 2020 16:17:29 -0400 by biohazardep