如何从php文件中调用javascript函数?

时间:2016-02-08 13:45:27

标签: javascript php

在我的PHP代码中,我有一个变量$password,我想在javascript函数中编辑它,该函数位于.js文件中。这意味着将$password作为参数传递给函数并将返回值保存到变量中。

我该怎么做?

2 个答案:

答案 0 :(得分:0)

我知道你可以尝试将它添加到你的PHP代码中:

echo '<script type="text/javascript"> drawChart(); </script>';

它将访问您的脚本,但您应该尝试使用AJAX。

希望它适合你

答案 1 :(得分:0)

以下是如何使用jQuery和Ajax:

  

getPassword.php

<?php
session_start();

$_SESSION['password'] = "whatever";

header("Content-Type: application/json");
echo json_encode(array("password" => $_SESSION['password']));
?>
  

Javascript部分,不要忘记包含jQuery

    // Let's get the password !
    $.ajax({url: "http://yoursite/getPassword.php", dataType: "JSON"}).done(function(response) {
        // Stocking the password here
        var password = response.password;

        // Do whatever you wan't with the password
        password = processPassword(password);

        // Post the password to php
        $.post("http://yoursite/setPassword.php", {password: password});
    });
  

最后,setPassword.php

<?php

session_start();

if (!empty($_POST['password'])) {
    // Retrieving the password sent by ajax in session
    $_SESSION['password'] = $_POST['password'];
}