在JavaScript弹出框中显示php变量


Display php variable into a JavaScript popup box

我有一个php文件,它连接到MySql数据库并从特定表中读取最后一个条目。我想做的是使用JavaScript弹出框将表中的最后一个条目显示(回显)到外部html文件中下面我有PHP文件(运行良好)和html文件的代码,但不幸的是,我不知道如何将PHP变量传递给JavaScript函数。

非常感谢。

php文件是这样的:

    <?php
    // 1. Create a database connection
    $connection = mysql_connect("localhost","root","password"); 
    if (!$connection) {
        die("Database connection failed: " . mysql_error());
    }
    // 2. Select database to use 
    $db_select = mysql_select_db("manage_projects",$connection);
    if (!$db_select) {
        die("Database selection failed: " . mysql_error());
    }
    // 3. Perform database query
    $result = mysql_query("SELECT survey_desc FROM subjects ORDER BY id DESC LIMIT 0,1", $connection);
    if (!$result) {
        die("Database query failed: " . mysql_error());
    }
    // 4. Use returned data
    while ($row = mysql_fetch_array($result)) {
        echo $row["survey_desc"]."<br />";
    }
    // 4.1 Alternative way to use returned data
    /* $row = mysql_fetch_array($result);
    echo $row["survey_desc"]."<br />";
    */
    // 5. Close connection
    mysql_close($connection);
?>

html文件:

    <html>
<head>
<script type="text/javascript src="myscript.php"">
    //if clicked Yes open new page if Cancel stay on the page 
    function popup(){
    var r=confirm("echo the php query here");
        if (r==true)
            {
            window.location = "http://example.com";
            }       
}
</script>
</head>
<body onload ="popup()">
</body>
</html>

您可以回显到JavaScript:

var r=confirm("<?php echo $relevant_variable; ?>");

此外,不建议在生产环境中使用die()。

<head>
<script type="text/javascript">
function popup(){
    var xhr=null;
    if (window.XMLHttpRequest) { 
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhr.onreadystatechange = function() {
      if(xhr.readyState == 4){ alert_ajax(xhr); }
     }
    xhr.open("GET", "myscript.php", true);
    xhr.send(null);
}
function alert_ajax(xhr){
   var docAjax= xhr.responseText;
   r=confirm(docAjax);
        if (r==true)
            {
                window.location = "http://example.com";
            }
}
</script>
</head>

使用PHP的json_encode()-函数:

var r = confirm(<?php echo json_encode("the php query here"); ?>);

由于JSON是JavaScript语法的一个子集,所以它为您转义并始终生成有效的JavaScript。

<?php 
    // Your php code;
    $myVar="your value that you want to pass to js";
?>
<html>
    <head>
     <script>
        //if clicked Yes open new page if Cancel stay on the page 
        function popup(){
        var mvar = '<?php echo $myVar ;?>';
        var r=confirm(mvar);
        if (r==true)
        {
            window.location = "http://example.com";
        }       
    }
    </script>
</head>
    <body onload ="popup()">
    </body>
</html>

只需将两个文件合并到一个php文件中即可。