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

时间:2011-08-09 12:45:52

标签: php jquery ajax json

我想使用json将数组从php发送到jquery。收到的数组,但我从数组中获取元素有问题。

我这样做了:

<?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>

当我遍历数组时,它会显示奇怪的元素!

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 ]

我怎样才能获得元素?

3 个答案:

答案 0 :(得分:3)

结果是一个JSON字符串。使用JSON.parse获取数组。

答案 1 :(得分:0)

在AJAX调用中,尝试添加dataType:“json”,或者您可以使用JSON.parse(result)从结果中获取JSON对象。

答案 2 :(得分:0)

您尚未设置dataType参数,请执行以下操作:

dataType: "json"