简体   繁体   English

如何在js中使用php值

[英]How to use php values in js

<?php 
    $query1="SELECT * FROM user_photos_offline WHERE ssmid='11'";
    $sql=mysql_query($query1);
    $count=mysql_num_rows($sql);

    while($row=mysql_fetch_assoc($sql)){
       $result=$row['name'].',';//resuts kani,raja,mahi,gobi
    }
?>
<script>
    var photos='<?php echo $result;?>';
</script>

I am getting only last value (gobi) but i want all values in js.我只得到最后一个值(gobi),但我想要 js 中的所有值。 i dont know how to get the all values in javascript我不知道如何获取 javascript 中的所有值

you have to add your results in an array:您必须将结果添加到数组中:

 $results=array();
 while($row=mysql_fetch_assoc($sql)){
     $results[]=$row['name'];//fill your array
 }

//then implode your array //然后内爆你的数组

<script>
    var photos='<?php echo implode(",",$results); ?>';
</script>

Instead of "overwriting" $result again and again within the while-loop make it an array and append the items.而不是在 while 循环中一次又一次地“覆盖” $result 使其成为一个数组并附加项目。
Then when outputting the variable use json_encode() to get a valid javascript object/array notation.然后在输出变量时使用json_encode()来获取有效的 javascript 对象/数组符号。

$result=array();
while($row=mysql_fetch_assoc($sql)) {
    // append the value of the field 'name' of the current record to $result
    $result[]=$row['name'].',';//resuts kani,raja,mahi,gobi
}
...
var photos=<?php echo json_encode($result);?>

The mysql_* extension is deprecated and will be removed with php 7. Better pick another api like mysqli or PDO_mysql. mysql_* 扩展已被弃用,将随 php 7 一起删除。最好选择另一个 api,如 mysqli 或 PDO_mysql。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM