PHP数组加载到的JavaScript [英] php array loading into javascript

查看:145
本文介绍了PHP数组加载到的JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一共PHP / JavaScript的小白。

so I am a total php/javascript noob.

我试图加载一个完整的PHP数组转换成JavaScript数组。
我写这为Javascript:

I'm trying load a full php array into a javascript array. I wrote this for Javascript:

    var names = new Array();
for(var i = 0; i < 48; i++) {
    names[i] = "<?php echo giveJS() ?>";
}

和本作的PHP

static $counter = 0;

function giveJS() {
    global $names;
    global $counter;
    $counter++;
    return $names[$counter]; 
}

我已经检查如果PHP数组正确填充数据。
当我写一个JavaScript输出线,像

I already checked if the php array is correctly filled with data. When I write a output line in javascript, like

document.write(names[10]);

它只是给我的PHP数组中的第一项,以便它似乎是每次for循环重复其初始化从零开始的php文件,因此将计数器设置为0。
我怎样才能解决呢?

it only gives me the first entry in the php array so it seems like everytime the for loop is repeated its initialising the php file from scratch and so setting the counter to 0. How can i fix that?

THX,
Linkee

Thx, Linkee

推荐答案

在PHP

//Bla being the php array you want to give to javascript. Create it however you like
$bla = array();
$bla[] = 'cat';
$bla[] = 'dog';
$bla[] = 'bat';
echo '<script>var myarray = '.json_encode($bla) .';</script>';

那么上面的code将输出一个脚本标签包含一个名为myArray varible,那么它的内容将是JSON指定上述阵列(json_en code格式的数组中的JavaScript内部syntax-阵列将可能看起来像['猫','狗','蝙蝠])

The above code will then output a script tag contain a varible called myarray, then contents of which will be JSON specifying the above array (json_encode formats the array in to javascript internal syntax- the array will probably look like ['cat','dog','bat] )

您可以再拿到从JavaScript数组值,像这样:

You can then get values from the JavaScript array as so:

<script>
 console.log(myarray[2]);
</script>

这篇关于PHP数组加载到的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆