我在使用arr.push创建dom时创建javascript数组。 但是在页面就绪函数上,它返回空数组
<script type="text/javascript">
var short_urls = [];
</script>
$(document).ready(function() {
console.log(short_urls);
});
<?
foreach ($d_json['result'] as $key => $value) {
?>
<script>
short_urls.push("<? echo $shorten_url ?>");
</script>
<?
}
?>
答案 0 :(得分:0)
<script type="text/javascript">
var short_urls = [];
$(document).ready(function() {
console.log(short_urls);
});
</script>
<?
foreach ($d_json['result'] as $key => $value) {
?>
<script>
short_urls.push("<? echo $shorten_url ?>");
</script>
<?
}
?>
答案 1 :(得分:0)
由于PHP将在任何javascript之前执行,您可以编写javascript变量而无需使用array.push
方法。但是,这个问题使用了php变量$shorten_url
- 那里定义了什么?我假设它是foreach
循环
Approach #1
-----------
<script type="text/javascript">
var short_urls = [];
<?php
foreach( $d_json['result'] as $key => $value ) {
$shorten_url='???';
echo "short_urls.push('{$shorten_url}');";
}
?>
$( document).ready( function() { console.log( short_urls ); } );
</script>
Approach #2
-----------
<script type="text/javascript">
<?php
$tmp=array();
foreach( $d_json['result'] as $key => $value ) {
$shorten_url='???';
$tmp[]=$shorten_url;
}
echo "var short_urls = ['".implode("','",$tmp)."'];";
?>
$( document).ready( function() { console.log( short_urls ); } );
</script>