如何在jquery中对php/ajax传递的数组进行切片


How to slice array passed by php/ ajax in jquery

我有一个页面,访问者可以使用下拉菜单来获取个人信息。

在变更调用之后,jquery通过ajax将人员的ID发送到php脚本,该脚本从数据库中提取数据。

因为数据应该在请求页面上的三个不同div中使用,所以数据会作为(php)数组发送回来。

现在我需要你的帮助。如何将数组(它有三个部分)拆分为三个javascript部分,这些部分可以发送到特定的div(比如div1、div2和div3)?

这是我的代码:

 $('#contentz').change(function(){
    var Value = $(this).val();  
    $.ajax({
        type: 'post',
        url: '/ajax.php',
        dataType: 'html',
        data: {action: Value},
        success:function( data){ 
    // I need to slice the array here           
            $("#veld1").html( data ); // result 1
            $("#veld2").html( data ); // result 2
            $("#veld3").html( data ); // result 3
    //alert(data); 
        }, 
        error:function (xhr, ajaxOptions, thrownError){
            //On error, we alert user
            alert(thrownError);
        }, 
        complete: function(){
            //alert('update success'); 
        }
    });
});

#contentz is the select/ dropdown.
#veld1, #veld2 and #veld3 are the divs that display the result.

将数组返回AJAX的最简单方法之一是将其编码为JSON、

$array = array("firstDivValue","secondValue","thirdDivValue");
echo json_encode($array);

并通过在AJAX中成功访问它

$.ajax({
        .......
        //Set it as JSON as we are now returning it
        dataType: 'json',
        .........
        success : function(data){
                $.each(data,function(i,value){
                    //Get value here
                    alert(value);
                });
         }

实现这一点的方法是以JSON格式输出数据。您可以在JSON中使用HTML,但必须尊重某些内容(尤其是转义某些字符)。下面是一篇快速文章的链接,该文章解释了在JSON中使用html必须做什么:http://www.thorntech.com/2012/07/4-things-you-must-do-when-putting-html-in-json/

var data = array("david","belly","Jay");
$("#veld1").html( data[0] ); 
$("#veld2").html( data[1] );
$("#veld3").html( data[2] );