0

是否可以将 php 返回分配给 js 变量?前任:

<script type='text/javascript'>
var h = <?php include'dbconnect.php';
    $charl = (some number from another sql query)
    $sql=mysql_query("selct type from locations where id='$charl'");
    echo $sql; ?> ;
if(h == "hostile") {
    (run some other js function)
}
</script>

我需要做的是从 charl(字符位置)获取单个文本值(类型)并将其分配给 java 脚本变量并在其上运行 if 语句。任何提示?

这是我的代码的更新。它不会返回任何错误,但不会以我想要的方式输出。它应该只返回应该等于敌对、城市、农场和类似的东西的[类型]。除非整个字符串在同一行,否则它不会运行。我相信它会返回整个字符串而不仅仅是回声(就像我需要的那样)

function check_hostile() { var h = '<?php session_start(); include"dbconnect.php"; $charid=$_SESSION[\'char_id\']; $charloc=mysql_fetch_array(mysql_query("select location from characters where id=\'$charid\'")); $charl=$charloc[\'location\']; $newloc=mysql_fetch_array(mysql_query("select type from locations where id=\'$charl\'")); echo $newl[\'type\']; ?>'; 
if(h == "hostile") { 
 if(Math.random()*11 > 8) { 
  find_creature(); 
 } 
}
$("#console").scrollTop($("#console")[0].scrollHeight);
}

这是运行时警报功能的输出。

<?php session_start(); include"dbconnect.php"; $charid=$_SESSION['char_id']; $charloc=mysql_fetch_array(mysql_query("select location from characters where id='$charid'")); $charl=$charloc['location']; $newloc=mysql_fetch_array(mysql_query("select type from locations where id='$charl'")); print $newloc['type']; ?>
4

2 回答 2

2

改成这个

var h = <?php include "dbconnect.php";
$charl = (some number from another sql query)
$sql=mysql_query("selct type from locations where id=$charl");
$row = mysql_fetch_row($sql);
echo json_encode($row["type"]); ?>;

json_encode()将 PHP 值转换为可以注入脚本的有效 Javascript 表示。

于 2013-05-22T08:16:37.553 回答
1

是的,这是可能的,而且是相当普遍的做法。

但是你的代码有一个小问题,它返回一个字符串,所以你必须在javascript中用引号将它括起来。

我已经更新了您的代码以解决这个小问题并提高代码的可读性:

<?php 

include'dbconnect.php';
$charl = (some number from another sql query)
$sql=mysql_query("select type from locations where id='$charl'");

if (mysql_num_rows($sql) > 0) {
    $row = mysql_fetch_array($sql);
    $h = $row['type'];
} else {
    $h = null;
}

?>

<script type='text/javascript'>

var h = '<?php echo $h; ?>';
if(h == "hostile") {
    (run some other js function)
}

</script>
于 2013-05-22T08:20:48.873 回答