How To Call Spring MVC Controller From JQuery Ajax

2019-08-18 08:49发布

i am attempting to call Spring controller method from JQuery ajax call, but its not navigate to corresponding view.

First i am verifying login details by calling authenticateLogin() Spring controller function from ajax call, after successful validate i need to forward the request to corresponding view page, i have tried with below code but its not navigate to another page.

Javascript function:

function authenticatePricingCalcLogin() {
    var login = {
            userName : $("#username").val(),
            password : $("#password").val()
    };

    $.ajax({type: "POST",
        url: CONTEXT_PATH+"authenticateLogin",
        data:JSON.stringify(login),
        contentType : 'application/json; charset=utf-8',
        dataType : 'json',
        success: function (response) {
            if (response != null) {
                if (response.errorMsg != null && response.errorMsg != "") { // Login Error
                    alert(response.errorMsg);
                } else {
                     // Here i need to call spring controller method and to redirect to another page

                     // I have tried
                     $.ajax({type: "GET",
                            url: CONTEXT_PATH+"navigateMainPage",
                            data:JSON.stringify(loginDO),
                            contentType : 'application/json; charset=utf-8',
                            dataType : 'json'
                    });
                }
            }
        }
    });
}

AuthController.java

@RequestMapping(value = "/authenticateLogin", method = RequestMethod.POST)
public @ResponseBody LoginDO authenticateLogin(@RequestBody Login login){
    return authService.authenticateLogin(loginDO);
}


@RequestMapping(value = "/navigateMainPage", method = RequestMethod.GET)
public String navigateMainPage(@ModelAttribute("loginDO") Login login,HttpServletRequest request, Model model) {
    try {
        // Need to set User Name in session variable
    } catch (Exception e) {

    }
    return "auth/mainPage";
}

2条回答
迷人小祖宗
2楼-- · 2019-08-18 09:38

Please add / in your path

url: CONTEXT_PATH+"/authenticateLogin",

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-08-18 09:39

Hi friend I don't have Comment authority so just answering your question.just comment data part if it is GET Type request and remove it form java side @ModelAttribute("loginDO") Login login, Otherwise just make it POST and check any CSRF token is there or not for safe side.

查看更多
登录 后发表回答