php foreach中的javascript加载器
I'm trying to make a little javascript loader. My code:
<?
//COUNT TOTAL PURCHASE INVOICES
$i = 0;
foreach($xml->tr as $purchase)
{
$i++;
}
$steps = 100 / $i;
$steps = str_replace(',', '.', $steps);
foreach($xml->tr as $purchase)
{
?>
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
var loaderValue = $("#loaderValue").val();
newLoaderValue = parseFloat(loaderValue) + parseFloat("<?=$steps?>");
$("#loaderValue").val(newLoaderValue);
$(".connect_loader").width(newLoaderValue+"%");
});
</script>
<?
}
?>
The script worked but the problem is that the javascript runs after php is ready so the loader is in one step at 100%.
Is there another simple way to do this?
Your question is a bit confusing.
You have to know that the PHP is used server side and the javascript client side.
The script worked but the problem is that the javascript runs after php is ready so the loader is in one step at 100%.
So this behavior is normal.
The best way to do what you want to do is to make a Javascript function which do an Ajax call and increment your loader depends on the result of the function.
I hope this works.
<?php
//COUNT TOTAL PURCHASE INVOICES
$i = 0;
foreach($xml->tr as $purchase)
{
$i++;
}
$steps = 100 / $i;
$steps = str_replace(',', '.', $steps);
?>
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
for(var x = 0; x <= <?php echo $i ?>; x++){
var loaderValue = $("#loaderValue").val();
newLoaderValue = parseFloat(loaderValue) + parseFloat("<?php echo $steps ?>");
$("#loaderValue").val(newLoaderValue);
$(".connect_loader").width(newLoaderValue + "%");
}
});
</script>
PHP is not visible to the client. The server will process the PHP part of your code and generate a html page which the client will see.
This means you cannot use PHP during runtime.
Try to store whatever values you need into Javascript variables and use those instead.
A simple way to understand this is to view page source on your webpage... You can see the resultant html code.