我已经看到了一些关于将PHP数组传递给外部JavaScript文件的问题,但我无法理解。我知道如何将PHP数组传递给内部JavaScript文件,但不知道如何将它们传递给外部JavaScript文件。
编码
<?php
$a = array("Apple","Orange","Grape");
?>
<script type="text/javascript">
var jArray= <?php echo json_encode($a); ?>;
for(var i=0;i<3;i++){
alert(jArray[i]);
}
使用此代码,JS 文件 (测试.js)
for(var i=0;i<jArray.length;i++){
alert(jArray[i]);
}
PHP 文件 (测试.php)
<?php
$a = array("Apple","Orange","Grape");
?>
<script type="text/javascript">var jArray =<?php echo json_encode($a); ?>;</script>
<script type="text/javascript" src="test.js"></script>
你不能
直接在外部js
文件中使用 php 代码,给定的代码是,
<?php
$a = array("Apple","Orange","Grape");
?>
<script type="text/javascript">
var jArray= <?php echo json_encode($a); ?>;
for(var i=0;i<3;i++){
alert(jArray[i]);
}
</script>
I think you can change the code as,
//Declaring the array in php
<?php
$a = array("Apple","Orange","Grape");
?>
//Assigning the json encoded format to javascript
<script type="text/javascript">
var jArray= <?php echo json_encode($a); ?>;
</script>
//You can use the jArray in the external js file
<script type="text/javascript" src="externaljsfile.js" >
你不能像
传递给内部那样将数据传递给外部JavaScript文件。
但是,解决方案可以是:
<script type='text/javascript'>
// here you retrieve datas from PHP and use them as global from your external
var myArray = <?php echo json_encode($a); ?>;
</script>
<script type='text/javascript' src='externalJavascript.js'></script>
或者,另一种解决方案可能是使用 AJAX 请求从外部文件获取数据。