Home  >  Article  >  Backend Development  >  在js中 怎么循环输出php数组

在js中 怎么循环输出php数组

WBOY
WBOYOriginal
2016-06-13 12:10:111407browse

在js中 如何循环输出php数组

本帖最后由 A9925 于 2014-11-20 18:11:40 编辑 现在进退两难,退到php,js要加载东西。
                          退到js, 又想要取出php的数据变量。

怎么办?请教了,谢谢!

<br /><script type="text/javascript"><br />					<br /><br />				var tree_gen="<?php echo $arr[0]['ConstrProjName'];?>";  //可以赋到值<br />				var tree_len="<?php echo count($arr);?>"			      //可以赋到值<br /><br />				if (document.getElementById) {	<br />					var tree = new WebFXTree(tree_gen);<br />					tree.setBehavior('classic');<br /><br />						for (var i=0;i<tree_len;i++){<br />				<br />						var e = new WebFXTreeItem("<?php echo $arr[i]['ConstrProjName'];?>");  //此时,i 变量得不到值,也就是不能用。 后边的document.write也都输出不了了。<br />						tree.add(e);<br />						document.write("888");<br /><br />                       <br />						}<br />					document.write(tree);<br />					tree.expandAll();<br />				}<br /><br />					document.write("999");<br />					</script><br />


var e = new WebFXTreeItem("");  
这里边的$arr[i]['ConstrProjName'] 是要动态获取用的值。

现在怎么整啊?给开个窍吧,谢谢!

------解决思路----------------------
php数组序列化为js数组js就可以直接用了
------解决思路----------------------
 var e = new WebFXTreeItem(""); 
你这句话不能这么写因为在服务器端执行PHP时不会解析你的js东西你那个i不会识别的。
当发到客户端时你的PHP代码又没有了所以括号里面永远不会识别的。
你应该在第六行将PHP数组$arr转换成js数组或者JSON对象(我推荐用JSON对象)
然后把你的for循环变成for in循环遍历你接收那个对象就行了。
------解决思路----------------------
改成这样试试。

<br /><script type="text/javascript"><br />                     <br /> <br />var tree_gen="<?php echo $arr[0]['ConstrProjName'];?>";  //可以赋到值<br />var tree_len="<?php echo count($arr);?>"                  //可以赋到值<br />var arr = <?php echo json_encode($arr) ?>;                // 先把php数组转为json<br /><br />if (document.getElementById) {   <br />    var tree = new WebFXTree(tree_gen);<br />    tree.setBehavior('classic');<br /><br />        for (var i=0;i<tree_len;i++){<br /> <br />        var e = new WebFXTreeItem(arr[i]['ConstrProjName']); // 改为读json数组<br />        tree.add(e);<br />        document.write("888");<br /><br />        <br />        }<br />    document.write(tree);<br />    tree.expandAll();<br />}<br /><br />document.write("999");<br /></script><br />
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn