dtkz3186
dtkz3186
2011-08-09 12:45

如何从php中获取jquery中的数组元素

  • json
  • php
  • ajax
  • jquery

I want to send array from php to jquery using json. the array in received but I have a problem to take elements from array.

I did this:

<?php
    $result[0] = 1;
    $result[1] = 6;
    echo json_encode($result);
?>

<script type="text/javascript">
$("#saveOrder").click(function(){           
    var customerName = $('input#customerName').val();
    var param = {"customerName":customerName,"action":"addOrder"};
    $.ajax({
            url: "controllers/Order.controller.php",  
            type: "POST",     
            data: param,                
            cache: false,       
            success: function (result) {        
        alert("result"+result);
        $.each(result,function(i,elem){
            alert(i+"_"+elem); 
        });

        var suc = result[0];
        alert("suc"+suc);
        var orderId = result[1];
        alert("id"+orderId);
                if (suc==1) {     
                    $('#resultMsg').text("success");  

                } else {              
            $('#resultMsg').text("error");  
        }
            }       
        });
        });
</script>

when I iterate through array, it display strange elements!

first,second, third and forth 
       loops : display nothing
fifth loop   : display [
sixth loop   : display 1
seventh loop : display ,
eighth loop  : display 6
ninth loop   : display ]

how can I get the elements?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

3条回答