开发者

Can you call JavaScript function from PHP loop?

开发者 https://www.devze.com 2023-03-24 19:11 出处:网络
I am wounding if I can do this, as I am trying this from last 2 days but no success. I want to run JavaScript function from PHP

I am wounding if I can do this, as I am trying this from last 2 days but no success.

I want to run JavaScript function from PHP

PHP example

<div id="meprocess"></div>
<?php
for($i=1;$i<=10;$i++)
{
?>
<script>
jfun(<?php echo $i;?>);
</script>
<?php
}
?>

JavaScript

<scr开发者_JS百科ipt type="text/javascript">

function jfun(n)
{
html="Loop is on" + n;
$("<div>"+ html +"</div>").appendTo("div#meprocess");   
}
</script>

I am trying to generate a page which print loop number one by one.

But I got error jfun is not defined.

What I can understand my JavaScript function is not ready at the time of PHP execution. Is there any way round, like running the PHP loop when DOM/Page is ready so that the JavaScript function will be ready that time, or any other way round.


You have to define that function before calling it

http://sandbox.phpcode.eu/g/15b02.php

<div id="meprocess"></div>
<script type="text/javascript">

function jfun(n)
{
html="Loop is on" + n;
$("<div>"+ html +"</div>").appendTo("div#meprocess");   
}
<?php
for($i=1;$i<=10;$i++)
{
?>
jfun(<?php echo $i;?>);
<?php
}
?>
</script>


Your PHP code is generating (in a very bad way..) some javascript code that will be executed by the script. Although it should work, this is definitely not the best way to do that - you should run the loop on the js-side, eventually passing values from your PHP script..

However:

The "undefined function" problem is given since you try to run the code before the function is created; using jQuery, to make some code executed only after everything is loaded, use:

$(document).ready(function(){
// Your code here..
})

or just

$(function(){
// Your code here..
})

As described here: http://api.jquery.com/ready/

For the for loop, you should generate some js like this:

<div id="meprocess"></div>
<script type="text/javascript">
for (i=1; i<=10; i++) {
jfun(i);
}
</script>

..maybe, generating the min/max values from the PHP script:

<?php
  $min = 1;
  $max = 10;
?>
<div id="meprocess"></div>
<script type="text/javascript">
for (i=<?php print $min; ?>; i<=<?php print $max; ?>; i++) {
jfun(i);
}
</script>

..that's more good practice than writing N function calls in order to loop..


First of all, ensure that your javascript function is above function uses.

Or try with <script>jfun("<?php echo $i;?>");</script>


Write the code before the PHP code. In that case the function jfun is known.

0

精彩评论

暂无评论...
验证码 换一张
取 消