【问题标题】:Data is not being passed from ajax to controller数据没有从 ajax 传递到控制器
【发布时间】:2021-01-21 09:42:22
【问题描述】:

我正在尝试进行 google 身份验证。在 add.php(templates file) 我写了这段 javascript 代码。

function singIn() {//<------this is called when button is pressed

firebase.auth()
            .signInWithPopup(provider)
            .then((result) => {
                console.log(result);
                var credential = result.credential;

                // This gives you a Google Access Token. You can use it to access the Google API.
                var token = credential.accessToken;

                // The signed-in user info.
                var user = result.user;

                var userInfo = JSON.stringify(user); //to Post
$.ajax({
method: “POST”,
url: “<?= Router::url(array('controller' => 'Users', 'action' => 'googlesignin')); ?>”,
data: {
userInfo
},
success: function(data) {
console.log(“Signed in google!”);
},

                error: function(param) {
                    console.log("Something went wrong" + param.responseText.message);
                    console.log("-----------------------");
                    console.log(param);
                }
            });

我得到了 google pop,一切正常,没有任何错误,但数据没有传递给控制器​​。我的控制器

public function googlesignin(){

    echo $_POST['data']['email'];
    die;
}

我也加了这个

$builder->connect(’/’, array(‘controller’ => ‘Users’, ‘action’ => ‘googlesignin’));

在 routes.php 中。

谁能告诉我问题出在哪里?

【问题讨论】:

  • 这是 cakephp-4
  • 首先,使用 CakePHP,您永远不应该直接访问超全局变量,您应该始终使用 CakePHP 提供的抽象 API!在这种情况下,这将是请求对象。话虽如此,首先在浏览器的网络控制台中检查 AJAX 请求,payload 究竟是什么样的,以及正在发送什么标头(您手动将数据编码为 JSON,然后将其传递给一个对象,这将不会像你想象的那样)?另请注意,POST 数据中不会有data 键,data 只是 jQuery 使用的选项名称。

标签: ajax firebase-authentication controller google-signin cakephp-4.x


【解决方案1】:

在阿贾克斯

$.ajax({
  // ...
  headers: {
    "Accept":"application/json"
  }
  //...

在你的控制器中

public function googlesignin(){

   $post = $this->request->getData(); // All post data available here
   // pr($post); // print all data
   echo $post['data']['email'];
   die;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-29
    • 2019-12-17
    • 1970-01-01
    • 2018-11-17
    • 2020-06-08
    • 2016-07-08
    • 2015-12-28
    • 2015-04-08
    相关资源
    最近更新 更多