douna6802 2014-05-30 19:26
浏览 54
已采纳

如何将php js变量改为jquery文件

how i can parse an Variable (php with js script) to an js file (jquery)?

This is what i do:

<script type='text/javascript'>
    <?php
    session_start();
     $var1 = $_SESSION['one'];
     $var2 = $_SESSION['two'];
      $con = mysqli_connect("");
      if (mysqli_connect_errno()) {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();}

      $result = mysqli_query($con,"Select name FROM  table WHERE one < '". $var1 . "' OR two < '". $var2 . "'");
      $rows=array();

      while($row=mysqli_fetch_array($result))
      {
      $rows[]=$row["name"];
      }

      $js_array = json_encode($rows);
      echo "var stat = ". $js_array . ";
";

       ?>

      </script>

In my js file i have this:

$(document).ready(function($)
{
for (var x = 0; x < stat.length; x++) {

    $(".class#" + stat[x]).css("background-color", "#e74c3c");

    alert(stat);
}});

My browser show this :

var stat = ["a1","a2","a3"];

How i can now get the php js_array to the stat variable (js)?

  • 写回答

1条回答 默认 最新

  • douyakan8924 2014-05-31 01:13
    关注

    Alternatively, since your using jquery, you could use $.each() function. This is very useful to what you want to achieve. Consider this example:

    <div class="class" id="a1" style="width: 50px; height: 50px;"></div>
    <div class="class" id="a2" style="width: 50px; height: 50px;"></div>
    <div class="class" id="a3" style="width: 50px; height: 50px;"></div>
    
    <script src="jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
    
        var stat = null;
        <?php
        // sample data
        $array_from_db = array('a1', 'a2', 'a3');
        $data = json_encode($array_from_db);
        echo "stat = $data;"; // assign it to stat
        ?>
    
        // use $.each();
        $.each(stat, function(index, element){
            // random colors for example's sake
            var color = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
            $('.class#'+element).css({backgroundColor: color});
        });
    
    
    });
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应