简体   繁体   English

将javascript响应变量传递给spring控制器函数

[英]pass javascript response variable to spring controller function

The following javascript code works with the facebook login window appearing and allowing a user to login. 以下javascript代码与出现的facebook登录窗口一起使用,并允许用户登录。 The response values are captured and I know it works as alerts appear where setup but I cannot pass the value back to a controller method. 捕获响应值,我知道它可以在设置中出现警报,但我无法将值传递回控制器方法。

 @RequestMapping(value ="/getAccessToken" , method = RequestMethod.POST)
 public @ResponseBody String getAccessToken(@RequestBody String token){

     System.out.println(token);

     return token;
  } 

Javascript method called: Javascript方法调用:

    function doLogin() {
        FB.login(function(response) {
        alert(response);
        console.log(response);
        if (response.authResponse) {
                    alert(response.authResponse.userID);
                    alert(response.authResponse.accessToken);
                    var Token = response.authResponse.accessToken;
                    alert(Token);
                    $.ajax({
                        type: "POST",
                        url: "/HelloController/getAccessToken",
                        data: Token,
                        success: function (result) {
                              alert("Token");
                        },
                        error: function (result) {
                              alert("oops");
                        }
                    });
                     document.getElementById('loginBtn').style.
         display = 'none';
         getUserData();
        }}, {perms:'manage_pages', 
       scope: 'email,public_profile', return_scopes: true});
     };

The error I get is the following: 我得到的错误如下:

WARN 25660 --- [nio-8080-exec-9] 
o.s.web.servlet.PageNotFound             : 
Request method 'POST' not supported

Appreciate responses. 感谢回应。

The problem could be that you are using a new version of JQuery that sends request data as post form data instead of JSON as default. 问题可能是您正在使用新版本的JQuery,它将请求数据作为后期表单数据而不是JSON发送为默认值。 Try changing your ajax call to the following. 尝试将您的ajax调用更改为以下内容。 The form data would not be recognized by your controller so if this is the case you should see a 404. 您的控制器无法识别表单数据,因此如果是这种情况,您应该看到404。

$.ajax({
        type: "POST",
        traditional: true,
        url: "/HelloController/getAccessToken",
        data: JSON.stringify(Token),
        success: function (result) {
           alert("Token");
        },
        error: function (result) {
          alert("oops");
        }
      });

For reference see this post: Send JSON data via POST (ajax) and receive json response from Controller (MVC) 供参考,请参阅以下文章: 通过POST(ajax)发送JSON数据并从Controller(MVC)接收json响应

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

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