Please provide help on how to assign php array values to javascript array
----------- Using below php code I am storing data in php array -----------
<?php
$str_query="SELECT title,description FROM tablename ORDER BY title";
$rs_sch=GetRecordset($str_query);
$int_count=0;
$schd_arr = array();
while(!$rs_sch->EOF())
{
$schd_arr[$int_count] = $rs_sch->Fields("title").": ".$rs_sch->Fields("description");
$rs_sch->MoveNext();
$int_count++;
}
?>
----- Using below javascript code I am trying to store php array data into javascript array -----
Please let me know what and how to write variable at below 2 mentioned locations so my code can work.
<script type="text/javascript" language="javascript">
var pausecontent=new Array()
for (sch_cnt=0; sch_cnt<*Here I want to assign value of $int_count php variable*; sch_cnt++)
{
pausecontent[sch_cnt]=<?php *Here I want to assign php array and counter values (something like this - $schd_arr[sch_cnt];)* ?>;
}
</script>
Thank you in advance, KRA
You can directly use the json_encode
function. It is easy to use and produces valid javascript so is very stable:
<script type="text/javascript">
var pausecontent = <?php echo json_encode($php_array); ?>;
</script>
You can't loop like that, you need to loop the PHP array and push
into javascript array:
<script type="text/javascript" language="javascript">
var pausecontent = new Array();
<?php foreach($schd_arr as $key => $val){ ?>
pausecontent.push('<?php echo $val; ?>');
<?php } ?>
</script>
I think you'd best get the array to your javascript first. That would be something like this:
var theVariableYouWantTheArrayIn = <?php echo json_encode($theArrayYouWantInJavascript); ?>
After that it is a normal js array, so you can use properties like .length which will presumably make the loop much easier.
I had the same problem doing this but finally found the best solution
<script>
var arr=[];
arr.push('<?php
include('conn.php');
$query = "SELECT *FROM c group by name";
$res = mysqli_query($conn,$query) or die(mysqli_error($conn));
while($data = mysqli_fetch_array($res))
{
echo $data["name"];
}
?>');
</script>
Above both answers in good.
您可以同时使用以下两种方法:
for (sch_cnt=0; sch_cnt<?php echo $int_count; ?>; sch_cnt++)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.