문제

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 :

$an_array=array();
$an_array[]='Element 1';
$an_array[]='Element 2';
$an_array[]='Element 3';
$array_js=implode(",",$this->js_pagina); //join elements in a string

jQuery :

//Converter
window.array=new String('<?php echo $array_js?>');
window.array=window.js_pagina.split(",");
//Iterator
$.each(window.array, function (i, elem) 
{
        alert(elem);
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top