使用Callback将PHP变量传递给JavaScript

时间:2016-03-22 09:01:58

标签: javascript php jquery ajax

我想借助JavaScript功能通过Ajax验证密码。

如果成功,我想传回变量(boolean,true或false)并根据回调在我的PHP文件中执行某些操作。

但这不起作用。这是我的代码:

PHP文件:update.php

<input href="javascript:void(0);" role="button" ype="submit" value="Submit" onclick="ValidatePassword()>'

JAVASCRIPT:ValidatePassword()

在我的Javascript函数中,我使用此ajax调用检查密码,如果成功,则应将结果回调到php函数。

 $.ajax({
    type: "POST",
    url: "checkpw.php",
    data: dataString,
    cache: false,
    success: function(response)
    {
        if (result != -1 )
        {
            $("#passwd").val('');

            // RETURN TO PHP FILE update.php -> PW IS VALID
        } else {
            // RETURN TO PHP FILE update.php -> PW IS INVALID
        }
    }
});

PHP文件:update.php

现在我想在php函数中使用回调,如:

<?php

if (passwordCallback == true)
...
else
...

?>

我应该在ajax成功函数中将该值返回到php文件?

2 个答案:

答案 0 :(得分:1)

您需要编写一个JavaScript函数,如:

function sendReturnToPHP(url, result) {
  $.ajax({
    type: "POST",
    url: url,
    data: JSON.parse(result),
    cache: false,
    success: function(response) {}
  });
}

现在您可以在请求成功时轻松调用它。

答案 1 :(得分:1)

正如我在评论中所建议的那样,如果编码不正确,可能会导致安全问题。如果编码正确,那么当它只需要完成一次时,它最终会进行两次密码检查。

相反,你可以做的是:

 $.ajax({
    type: "POST",
    url: "checkandupdate.php", //Combination of both
    data: dataString,
    cache: false,
    success: function(response)
    {
        if (result != -1 ) {
            $("#passwd").val('');    
        }
    }
});

文件checkandupdate.php

<?php
require "checkpw.php"; // Or whatever you need to do to validate the password
// At this point "checkpw.php" determined if the password is valid and(ideally) you can check the outcome
//Assume we store the outcome of the check in $passwordIsValid as a boolean indicating success
if ($passwordIsValid) {
    //Do whatever you need to do when the password is valid
    echo "1"
}
else {
   // Do whatever you need to do when the password is invalid
   echo "-1";
}
?>
相关问题