繁体   English   中英

如何在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-在JSON的/

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM