-1

目前,我有一个 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);

?>
4

1 回答 1

1

要将数据传回调用脚本的 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);
}
于 2012-04-21T01:55:34.213 回答