如何将PHP变量传递回调用它的Javascript页面


How To Pass PHP Variables back to a Javascript Page that Called It

目前,我有一个Javascript文件(在客户端上运行),我从中调用PHP文件(在服务器上)。 PHP 文件完成后,我想将三个变量传递回客户端上运行的 javascript。 我想出了如何让javascript等待php文件完成执行,所以这不是问题。 问题是将变量传递回 javascript 文件。 这能做到吗? 我看到的所有例子都有某种混合的javascript/php文件。 我希望找到一些方法来传递php变量,就像jquery.ajax一样。 我不知道这是否可以做到,因为我对Javascript和PHP很陌生。谢谢

JavaScript:

<html>
    <head>
        <title>Login Page</title>
    </head>
    <script language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
    <script language="Javascript">
        function calculations(callback)
        {
            var x = <?php echo $username?>;
            alert(x);
            var password = window.prompt("Please Type Your Password");
        }//ends the calculations function
        function getUsername()
        {
            var username = window.prompt('Please Type Your Username');
            var temp = document.getElementById('temp');
            temp.innerHTML = username;
            jQuery.ajax(
                {
                    type: "POST",
                    url:"GetInfo.php",
                    data: "username="+username,
                    success: function(msg)
                            {callback.call();}
                });//ends the jQuery send

        }//ends the GetUsername function
    </script>
    <body onLoad=getUsername()>
        <div id="temp">This will show text</div>
    <body>
</html>

.php:

<?
//$username = $_POST['username'];
$username = "tom";
$inFile="MyID.config.php";
$handle=fopen($inFile, 'r') or die ("No credentials could be gotten because the file MyID.config.php would not open.");
$data='0';
do{
$data = fgets($handle);
$temp = substr($data,0, 10);
//echo $temp.strcmp($temp,'''username''')."'n";
}while (strcmp($temp, '''username''')!= 0);

$data = substr($data,15,strlen($username));
if (strcmp($data, $username == 0) )
{
    $read_in = fgets($handle);
    $x = substr($read_in,8,-3);
    $read_in = fgets($handle);
    $y = substr($read_in,8,-3);
    $read_in = fgets($handle);
    $salt = substr($read_in,11,-3);
}//ends the strcmp $data and $username if statement.
fclose($handle);
?>

要将数据传回调用脚本的 Javascript,只需像这样回显:

$value = 'foobar';
echo $value;

对于多个值,您可以将其作为 JSOn 对象传递回

$name = 'foobar';
$text = 'helloworld';
$value = 5;
//add to associative array
$result['name'] = $name;
$result['text'] = $text;
$result['value'] = $value;
// encode as json and echo
echo json_encode($result);

在 Javascript 端,你的回调函数将收到以下内容:

function callback(data){
    var result = JSON.parse(data);
    //access the members
    console.log(result.name);
    console.log(result.text);
    console.log(result.value);
}