如何在jquery中切片由php / ajax传递的数组

时间:2015-02-05 09:22:43

标签: javascript php jquery html ajax

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

在更改调用之后,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.

3 个答案:

答案 0 :(得分:1)

将数组返回到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);
                });
         }

答案 1 :(得分:0)

我将采用JSON格式输出数据。你可以在JSON中使用HTML,但是你必须尊重某些事情(特别是逃避某些字符)。这是一篇快速文章的链接,解释了在JSON中使用html必须采取的措施:http://www.thorntech.com/2012/07/4-things-you-must-do-when-putting-html-in-json/

答案 2 :(得分:0)

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