[英]Access a PHP array element by using a JavaScript variable as index
The code looks like this: 代码如下:
PHP file PHP文件
<?php
...
$arrayName = ['ArrayValue_0', ..., 'ArrayValue_n'];
...
php?>
JavaScript 的JavaScript
$('.elementClass').each(function(index, id) {
$(id).html('<?php echo $arrayName[index - 1]?>');
});
But you can't just insert a JavaScript variable like that into php tags so index is never received. 但是您不能仅将类似的JavaScript变量插入php标签,因此永远不会收到索引。 I know this can be done via AJAX but is there any other way?
我知道可以通过AJAX完成此操作,但是还有其他方法吗? Thanks in advance.
提前致谢。
Additional info: I've been told to do this in PHP so there's no posibility of switching the array to a JS file. 附加信息:有人告诉我在PHP中执行此操作,因此无法将数组切换为JS文件。
You can define arrayName
variable in JS and initialize it with the value from the server: 您可以在JS中定义
arrayName
变量,并使用服务器中的值对其进行初始化:
var arrayName = <?php echo json_encode($arrayName); ?>;
$(".elementClass").each(function(index, id) {
$(id).html(arrayName[index-1]);
});
What you're trying to do will not work. 您尝试执行的操作无效。 For example this:
例如:
$(id).html('<?php echo $arrayName[index - 1]?>');
The above will never, ever work, because PHP is run on a server , not on your user's browser. 上面的代码永远不会起作用,因为PHP是在服务器上运行的 ,而不是在用户的浏览器上运行的。
What you need to do is send the variable somehow to the server. 您需要做的是将变量以某种方式发送到服务器。 You have a plethora of options:
您有很多选择:
$_POST
variable $_POST
变量 $_GET
variable $_GET
变量 Remember, PHP runs on the server, which renders the page, which then in turn is read by your browser where you run Javascript. 请记住,PHP在运行服务器的服务器上运行,该服务器呈现页面,然后在运行Javascript的浏览器中读取该页面。 You can't paste PHP code into the page and expect it to be parsed by PHP!
您不能将PHP代码粘贴到页面中,并期望它能被PHP解析!
如果您希望从服务器获取信息(PhP在服务器上运行),则需要返回服务器,因此在加载包含PhP数组完整内容的页面时,您可以即时创建javascript变量,或者您可以使用ajax返回服务器,而无需刷新整个页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.