简体   繁体   中英

How To Call Spring MVC Controller From JQuery Ajax Call

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";
}

Please add / in your path

url: CONTEXT_PATH+"/authenticateLogin",

嗨,朋友,我没有评论权限,所以只需回答您的问题即可。如果它是GET Type请求,请评论它的数据部分,并将其从java side @ModelAttribute("loginDO") Login login删除,否则请@ModelAttribute("loginDO") Login login POST并检查任何CSRF出于安全考虑,令牌是否存在。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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