使用 Callback 将 PHP 变量传递给 JavaScript

Pass PHP variable to JavaScript with Callback

本文关键字:JavaScript 变量 Callback PHP 使用      更新时间:2023-09-26

我想借助Ajax函数通过JavaScript验证密码。

如果成功,我想传回变量(布尔值、真或假),并根据回调在我的PHP文件中做一些事情。

但这行不通。这是我的代码:

PHP 文件:更新.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 文件:更新.php

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

<?php
if (passwordCallback == true)
...
else
...
?>

ajax成功函数中,我应该怎么做才能将值返回到我的php文件?

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

相反,您可以做的是:

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

文件检查和更新.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";
}
?>

你需要编写一个JavaScript函数,如下所示:

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

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