简体   繁体   English

通过使用JavaScript变量作为索引来访问PHP数组元素

[英]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: 您有很多选择:

  1. Use a form and read a $_POST variable 使用表格并读取$_POST变量
  2. Append it to a URL and read a $_GET variable 将其附加到URL并读取$_GET变量
  3. Use AJAX and asynchronously send that variable to the server 使用AJAX并将该变量异步发送到服务器
  4. Return the whole array from PHP to your Javascript code 将整个数组从PHP返回到您的Javascript代码
  5. etc. etc. 等等等

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM