duancan65665 2013-05-22 08:14
浏览 25

将javascript var分配给php返回

Is it possible to assign a php return to a js variable? ex:

<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>

what I need to do is get a single text value (type) from the charl (character location) and assign it to a java script variable and run an if statement on it. any hints?

Here is an update on my code. it doesnt return any errors but its not outputting the way i want it to. it should return the [type] only which should be equal to hostile, city, farm, and stuff like that.it wont run unless the entire string is in the same line. I believe its returning the entire string and not just the echo (like i need it to)

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

Here is the output of an alert function when theis is run.

<?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条回答 默认 最新

  • douren7921 2013-05-22 08:16
    关注

    Change it to this

    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() will convert a PHP value into a valid Javascript representation that you can inject into your script.

    评论

报告相同问题?