如何将php中的字符串var传递给JS函数?

时间:2012-11-20 07:15:37

标签: php javascript html mysql

我查找与宠物小精灵相关的图像并用php显示它。然后我希望能够通过点击它“翻转卡片”。我第一次点击下来,但第二次点击将卡翻转回来是行不通的。我认为它是JS中我的php变量的语法:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">

<title>
'Murica!
</title>

<script>

function changeImage()
{

element=document.getElementById('pokemon_card')

if 
(element.src.match("http://dmisasi.files.wordpress.com/2010/12/david-pokemon-card-     back.jpg?w=750"))
{element.src="'.$result['image_url'].'";} //<- no idea how to express the php string variable here

else
{element.src="http://dmisasi.files.wordpress.com/2010/12/david-pokemon-card-back.jpg?     w=750";}

}

</script>

</head>

<body>

<?php

$dbhost = 'databasePlace';
    $dbname = 'mine';
    $dbuser = 'me';
    $dbpass = '******';

    $link = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);

    mysqli_select_db($link,$dbname);    


$name = $_GET["fname"];



                $query = sprintf("SELECT image_url, Type
                                  FROM Pokemon c
                                  WHERE c.name='%s'",
                mysqli_real_escape_string($link,$name));

    $result = mysqli_fetch_assoc(mysqli_query($link,$query));

    echo '<img id="pokemon_card" onclick="changeImage()" height="225" 
width="165" src="'.$result['image_url'].'"/>';

mysqli_close($link);

?>

</body>
</html>

5 个答案:

答案 0 :(得分:7)

最简单的方法是在Javascript中加入一个小PHP脚本,就像这样......

<script type="text/javascript">
function bla() {
    var thevar = "<?php echo $thevar; ?>";
}
</script>

换句话说,根据您的问题,您会将第{element.src="'.$result['image_url'].'";}行替换为第{element.src="<?php echo $result['image_url']; ?>";}

答案 1 :(得分:1)

用这一行替换你的行:

element.src = "<?= $result['image_url'] ?>";

或者你可以设置一个javascript var并调用它:

var imageUrl = "<?= $result['image_url'] ?>";

// ...

element.src = imageUrl;

答案 2 :(得分:1)

你必须使用

 json_encode

 <?php
  $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
  echo $t=json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}

 ?>

现在$ t你可以传入js函数

在js代码中:

<script type="text/javascript">
function you_fun_nm() {
    var val = <?php echo $t; ?>
     alert(val);
}

答案 3 :(得分:1)

尝试在javascript中编写php变量如下

{element.src="'<?php echo $result['image_url']; ?>'";}

答案 4 :(得分:1)

  1. 你必须修改你的Javascript函数,下面是修改版本

    function changeImage(image_from_db)
    {
        element=document.getElementById('pokemon_card')
    
        if 
        (element.src == "http://dmisasi.files.wordpress.com/2010/12/david-pokemon-card-back.jpg?w=750")
        {
            element.src = image_from_db;} //<- image_from_db is being passed by you PHP script
        else
        {
            element.src="http://dmisasi.files.wordpress.com/2010/12/david-pokemon-card-back.jpg?w=750";
        }
    }
    
  2. 然后在您的图片代码上调用上述功能

  3. enter image description here