[英]increment php variable in javascript
I am trying to increment a php variable in a javascript function: 我试图增加javascript函数中的php变量:
function border(){
<?php $var_drafts_display=0; ?>;
for(var i=0; i<5; i++)
{
<?php ++$var_drafts_display ; ?>;
}
var final_num='<?php echo $var_drafts_display; ?>';
alert(final_num);
}
But the php variable gets incremented only once ie alert(final_num)
shows 1. I know php is server side program and javascript is client side program, is that the main problem why php variable is not getting incremented. 但是php变量仅增加一次,即alert(final_num)
显示为1。我知道php是服务器端程序,而javascript是客户端程序,这就是为什么php变量没有增加的主要问题。 Also, I am not able to figure out why it is getting incremented only once. 另外,我无法弄清楚为什么它仅增加一次。
You're trying to mix server side code (PHP) with JavaScript code: 您正在尝试将服务器端代码(PHP)与JavaScript代码混合使用:
function border(){
<?php $var_drafts_display=0; ?>;
for(var i=0; i<5; i++)
{
<?php ++$var_drafts_display ; ?>;
}
var final_num='<?php echo $var_drafts_display; ?>';
alert(final_num);
}
will ultimately get turned into this: 最终会变成这样:
function border(){
;
for(var i=0; i<5; i++)
{
;
}
var final_num='1';
alert(final_num);
}
which will simply alert 1. 这只会警告1。
You'd want to do something like: 您想要执行以下操作:
function border(){
var draftsToDisplay = <?php echo $var_drafts_display=0; ?>;
for(var i=0; i<5; i++)
{
draftsToDisplay++;
}
alert(draftsToDisplay);
}
There is a great guide on the differences between client/server code, and some examples here . 关于客户端/服务器代码之间的区别,有很好的指南, 此处还有一些示例。
That kind of behavior is impossible. 这种行为是不可能的。 You need to clearly understand, how php and js works. 您需要清楚地了解php和js的工作方式。 PHP just compile web page html code on a server side and then it pass html code to a client. PHP只是在服务器端编译网页html代码,然后将html代码传递给客户端。 Client's web browser parsing that code and then execute all scripts. 客户的Web浏览器解析该代码,然后执行所有脚本。 So your js machine will see the next code: 因此,您的js机器将看到以下代码:
function border(){
for(var i=0; i<5; i++)
{
}
var final_num='1';
alert(final_num);
}
Are you displaying all iterations in individual alert box then you can do this: 您要在单个警报框中显示所有迭代,然后执行以下操作:
function border(){
<?php $var_drafts_display=0; ?>;
var final_num = 0;
for(var i=0; i<5; i++){
<?php $var_drafts_display++ ; ?>;
final_num='<?php echo $var_drafts_display; ?>';
alert(final_num);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.