如何将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)?

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>