简体   繁体   English

在php文件中调用函数并传递JavaScript变量

[英]Calling function in a php file and passing JavaScript variables

I have a file.php and inside a function. 我有一个file.php并在函数内。 Javascript Side, I use Ajax. Javascript方面,我使用Ajax。

$.ajax({
  type: "POST",
  url: "file.php",
  data: {param1: params1, param2: params2...},
  complete: function(data){
   /* code */
  }
});

Now in the file file.php, a function login exists. 现在,在文件file.php中,存在函数登录名。 My question how can I call the function login ? 我的问题如何调用函数登录? Thanks. 谢谢。

function ft_login($login, $password) {
    $u = new KVObject();
    $u->collection = "users";
    $u->loadFormArray(["login" => $login, "password" => $password]);
    if ($u->obj_id == null)
        return ["ERROR" => "Bad creditial"];
    if ($u->status == "blocked")
        return ["ERROR" => "Account need to be activated"];

    $token = md5(time());
    $_SESSION[$token] = $u->dataObject;
    return ["token" => $token, "user" => $u->dataObject];
}

The whole php file is executed. 整个php文件被执行。 So if you call ft_login inside file.php it gets executed. 因此,如果您在file.php中调用ft_login,它将被执行。 You can pass your parameters to that function. 您可以将参数传递给该函数。

Dont forget to json_decode your parameters. 不要忘记对参数进行json_decode。

You can pass another parameter instructing the PHP code what to do 您可以传递另一个参数来指示PHP代码该怎么做

$.ajax({
    type: "POST",
    url: "file.php",
    data: {request: 'login', password:userid, password:password},
    complete: function(data){
    }
});

And then in the file.php PHP code 然后在file.php PHP代码

<?php
function ft_login($login, $password) {

    . . .

}

if ( isset($_POST['request'] && $_POST['request'] == 'login' ) {
    if ( isset($_POST['login'], $_POST['password']) ) {
        $result = ft_login($_POST['login'], $_POST['password']);

        // do whatever with $result
    }
}

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

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