admin管理员组文章数量:1287627
I've seen some of the questions about the passing PHP arrays to an external JavaScript file, but I can't understand it. I know how to pass PHP arrays to internal JavaScript files but not how to pass them to external JavaScript files.
Coding
<?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]);
}
I've seen some of the questions about the passing PHP arrays to an external JavaScript file, but I can't understand it. I know how to pass PHP arrays to internal JavaScript files but not how to pass them to external JavaScript files.
Coding
<?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]);
}
Share
Improve this question
edited Jan 13, 2015 at 9:27
Makyen♦
33.4k12 gold badges92 silver badges125 bronze badges
asked Jan 13, 2015 at 9:22
HappyHappy
1,09111 silver badges28 bronze badges
2
- Use ajax to get variables from PHP – vaso123 Commented Jan 13, 2015 at 9:29
- Not possible to use javascript? – Happy Commented Jan 13, 2015 at 9:31
3 Answers
Reset to default 5use this code, JS File (test.js)
for(var i=0;i<jArray.length;i++){
alert(jArray[i]);
}
PHP File (test.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>
You cant use php code directly in your external js
file, the given code is,
<?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" >
You can't pass datas to external javascript file like you do to internals.
But, a solution can be :
<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>
Else, a different solution could be getting datas with an AJAX request from your external file.
本文标签: Pass Php Arrays to External Javascript FileStack Overflow
版权声明:本文标题:Pass Php Arrays to External Javascript File - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741310563a2371626.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论