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

时间:2021-07-03 13:38:59

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.

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

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 个解决方案

#1


3  

The result is a JSON string. Use JSON.parse to get the array.

结果是一个JSON字符串。使用JSON。解析以获取数组。

#2


0  

Inside your AJAX call, try adding dataType: "json" or you can use JSON.parse(result) to get a JSON object from your result.

在AJAX调用中,尝试添加数据类型:“json”,或者可以使用json .parse(result)从结果中获得json对象。

#3


0  

you have not set the dataType parameter, please do the following:

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

dataType: "json"

#1


3  

The result is a JSON string. Use JSON.parse to get the array.

结果是一个JSON字符串。使用JSON。解析以获取数组。

#2


0  

Inside your AJAX call, try adding dataType: "json" or you can use JSON.parse(result) to get a JSON object from your result.

在AJAX调用中,尝试添加数据类型:“json”,或者可以使用json .parse(result)从结果中获得json对象。

#3


0  

you have not set the dataType parameter, please do the following:

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

dataType: "json"