我有一个连接到MySql数据库的php文件,并从特定表中读取最后一个条目。我想要做的是,使用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>
答案 0 :(得分:4)
您可以回复JavaScript:
var r=confirm("<?php echo $relevant_variable; ?>");
此外,不建议在生产环境中使用die()。
答案 1 :(得分:0)
<?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文件中即可。
答案 2 :(得分:0)
<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>
答案 3 :(得分:0)
使用PHP的json_encode()
-function:
var r = confirm(<?php echo json_encode("the php query here"); ?>);
它为您逃脱并始终生成有效的JavaScript,因为JSON是JavaScript语法的子集。