将javascript var分配给php返回

时间:2013-05-22 08:14:27

标签: php javascript sql

是否可以将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语句。任何提示?

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

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

以下是运行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']; ?>

2 个答案:

答案 0 :(得分: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表示。

答案 1 :(得分: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>