如何在 jQuery 中迭代 PHP 数组?我在 php 中有一个名为 $viewfields
的数组。
如何使用 jQuery 迭代该数组的每个元素?
编辑 1
<?php foreach ($viewfields as $view): ?>
if(<?=$view['Attribute']['type'];?>=='text'||<?=$view['Attribute']['type'];?>=='number')
{
$("<input id=input<?=$view['Attribute']['sequence_no'];?> type= 'text' style= 'width:<?=$view['Attribute']['size'];?>px' data-attr=<?=$view['Attribute']['type'];?> ></input><br>").appendTo("#fb_contentarea_col1down21 #<?=$view['Attribute']['sequence_no'];?>");
}
如果我给
$.each(arrayfromPHP,function(i,elem){
}
如何在 jQuery 中编写 $view['Attribute']['type'] 的代码? 我想 elem['Attribute']['type'] 不起作用?
编辑2
elem['Attribute']['type'] 有效
最佳答案
var arrayFromPHP = <?php echo json_encode($viewFields) ?>;
$.each(arrayFromPHP, function (i, elem) {
// do your stuff
});
为了更好地理解事物是如何连接在一起的(感谢 Jonathan Sampson):
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var arrayFromPHP = <?php echo json_encode($viewFields) ?>;
$.each(arrayFromPHP, function (i, elem) {
// do your stuff
});
</script>
</head>
<body>
</body>
</html>
您当然可以将该 SCRIPT
标记放置在页面中的任何位置,或者您甚至可以从外部脚本引用 arrayFromPHP
作为 arrayFromPHP
被声明为全局的。
编辑
给定这个 PHP 数组:
$viewFields = array(
'Attributes' => array(
'type' => 'foo',
'label' => 'bar',
),
'Attributes' => array(
'type' => 'foo',
'label' => 'bar',
),
);
使用 jQuery 访问其元素将如下完成:
// json_encode() will output:
// {"Attributes":{"type":"foo","label":"bar"}}
$.each(arrayFromPHP, function (i, elem) {
alert(elem.type);
alert(elem.label);
});
关于php - 在 jQuery 中迭代 PHP 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1205892/