如何在 PHP 中使用 JavaScript 变量?
我正在尝试这段代码:
<script type="text/javascript">
for (i = 0; i < 5; i++) {
for (x = 0; x < 1; x++) {
$("#one" + i).html("<?php echo $arr["+i+"]["+x+"] ?>");
$("#two" + i).html("<?php echo $arr["+i+"]["+x+1+"] ?>");
};
};
</script>
没有显示错误,但内容也没有显示。
如何在 PHP 代码中使用 JavaScript 的增量变量?
谢谢
I am trying this code:
<script type="text/javascript">
for (i = 0; i < 5; i++) {
for (x = 0; x < 1; x++) {
$("#one" + i).html("<?php echo $arr["+i+"]["+x+"] ?>");
$("#two" + i).html("<?php echo $arr["+i+"]["+x+1+"] ?>");
};
};
</script>
No error is showed, but content also not.
How can I use the increment variable of JavaScript in PHP code?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使 JS 可以访问您的 PHP 数组(将其存储为 js 变量):
You may make your PHP-array accessible to JS(store it as a js-variable) :
您不能这样做。
Javascript 在客户端上运行,这是在所有 PHP 代码执行之后。
为什么不用 PHP 编写循环呢?例如,
You cannot do this.
Javascript runs on the client, which is after all PHP code has executed.
Why don't you write the loop in PHP instead? For example,
好吧,我试着给你一个简短的问题......虽然它可能很长。
PHP 是一种服务器端脚本语言,而 javascript 是一种客户端脚本语言。
这意味着 php 代码在服务器(例如 Apache)中解释和执行,而 javascript 代码在浏览器本身内部执行。
因此,您无法在浏览器中执行 php 代码。
对于您编写的代码,您可以简单地转换 php 中的两个
for
javascript 迭代。如果您确实需要在给定 javascript 变量的 php 中打印某些内容,您应该对 php 页面执行 AJAX 请求,该页面接收您的 javascript 值并返回您需要的 php 计算值。请首先查看这些参考资料:
http://en.wikipedia.org /wiki/Server-side_scripting
http://en.wikipedia.org/wiki/Client-side_scripting
Ok, I try to give you a short question..althought it may be very long.
PHP it's a Server-side scripting language, while javascript it's a Client-side one.
That's mean that the php code is interpreted and executeted in the server (e.g. Apache), and the javascript code is executed inside the browser itself.
So, there is no way you can execute php code inside of your brower.
for the code you have written you can simpli transform the two
for
javascript iteration in php. If you actually need to print something in php given a javascript variable you should do an AJAX request to a php page that recive your javascript value and returns back the php-calculated values you need.Please have a look at those references as a start:
http://en.wikipedia.org/wiki/Server-side_scripting
http://en.wikipedia.org/wiki/Client-side_scripting
由 php 解释器解释。如果实际的 php 文件中没有此块,则意味着您正在浏览器的上下文中执行。浏览器不知道 php,只知道您的 Web 服务器。因此,浏览器会将
解释为 HTML 元素,而该元素并不存在。
您需要将整个块移动到 php 文件中,如下所示:
<?php
is interpreted by the php interpreter. If you don't have this block in an actual php file, then that means you are executing in the context of the browser. The browser doesn't know about php, only your web server. Thus, the browser will interpret<?php
as an HTML element, which doesn't exist.You need to move your entire block into a php file, like so: