简体   繁体   English

如何从“另一个文件”中的JS访问PHP数组?

[英]How to access a PHP array from JS “in another file”?

I have seen this answer (and a couple others as well) and it provides an understandable way of accessing a PHP array. 我已经看到了这个答案 (以及其他几个答案 ),它提供了一种可理解的访问PHP数组的方式。 But in the example, the PHP and the JavaScript are in the same file. 但是在示例中,PHP和JavaScript位于同一文件中。

However, I can not write Javascript in my PHP file for some reasons, and what I am rather doing is invoking the JS present in another file. 但是,由于某些原因,我无法在PHP文件中编写Javascript,而我正在做的是调用另一个文件中存在的JS。 So I need to access an array from the PHP in the JS file. 因此,我需要从JS文件中的PHP访问数组。 How can I do that? 我怎样才能做到这一点?

I prefer it without AJAX ( if possible ) because I have not yet started learning AJAX. 我更喜欢不使用AJAX( 如果可能的话 ),因为我尚未开始学习AJAX。

You could use a JSONP approach: 您可以使用JSONP方法:

Make your PHP file output your data wrapped in a function call - something like this: 使您的PHP文件输出包装在函数调用中的数据-类似于:

callback(
  ['your', 'data', 'here']
);

To do this with a PHP variable you can do this: 要使用PHP变量执行此操作,可以执行以下操作:

callback(<?php echo json_encode($data) ?>);

Then in your JavaScript file do this: 然后在您的JavaScript文件中执行以下操作:

function callback(data) {
  alert( data.join(' ') ); // will alert 'your data here'
}

In your HTML file just include the above JS file and afterwards include another script tag that points to your php file: 在您的HTML文件中,仅包含上面的JS文件,然后再包含另一个指向您的php文件的脚本标签:

<script src="/path/to/local.js"></script>
<script src="http://yourserver.com/path/to/server.php"></script>

The browser will grab the first file, and evaluate the function declaration. 浏览器将获取第一个文件,并评估函数声明。 Then it will grab the second file, and see that it is a function invocation and immediately execute your function with the data as the argument. 然后它将抓取第二个文件,并看到它是一个函数调用,并立即以数据作为参数执行函数。

A quick and dirty solution would be to make your JavaScript file a PHP file and pass all the variables you need when including the script: 一个快速而肮脏的解决方案是将您的JavaScript文件变成一个PHP文件,并在包含脚本时传递所需的所有变量:

<script type="text/javascript" language="javascript" src="./script.php?var=<?php print(json_encode($var)); ?>"></script>

In the JavaScript file you can use the PHP variables like so: 在JavaScript文件中,您可以像这样使用PHP变量:

var a=JSON.parse(<?php print($_REQUEST['var']); ?>);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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