将javascript var赋值给PHP返回值


assigning javascript var to php return

是否有可能将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语句。有提示吗?

这是我的代码更新。它没有返回任何错误,但它没有按我想要的方式输出。它应该只返回[类型],它应该等于敌对、城市、农场等。它不会运行,除非整个字符串在同一行。我相信它返回整个字符串,而不仅仅是echo(我需要它)

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);
}

下面是alert函数运行theis时的输出。

<?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']; ?>

改成这个

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表示,您可以将其注入到脚本中。

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

但是你的代码有一个小问题,它返回一个字符串,所以你必须在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>