将Php数组传递到外部Javascript文件
我看到了一些关于将PHP数组传递到外部JavaScript文件的问题,但我不理解。我知道如何将PHP数组传递给内部JavaScript文件,但不知道如何将它们传递给外部JavaScript文件 编码将Php数组传递到外部Javascript文件,javascript,php,arrays,Javascript,Php,Arrays,我看到了一些关于将PHP数组传递到外部JavaScript文件的问题,但我不理解。我知道如何将PHP数组传递给内部JavaScript文件,但不知道如何将它们传递给外部JavaScript文件 编码 <?php $a = array("Apple","Orange","Grape"); ?> <script type="text/javascript"> var jArray= <?php echo json_encod
<?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]);
}
var-jArray=;
对于(var i=0;i,您不能像对内部文件那样将数据传递到外部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>
//在这里,您可以从PHP中检索数据,并将它们用作外部数据库中的全局数据
var myArray=;
否则,另一种解决方案可能是通过AJAX请求从外部文件获取数据。使用以下代码,
JS文件(test.JS)
for(var i=0;i;
您不能在外部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" >
var-jArray=;
对于(var i=0;i;
//您可以在外部js文件中使用jArray
使用ajax从phpn获取变量不可能使用javascript?
<?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>
<?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" >