在jQuery中处理多个内容的回调参数?

时间:2016-12-28 09:12:27

标签: php jquery

是否有可能从php发送两个不同的数组到jQuery?试图从php获取两个不同的数组到两个不同的回调参数,在jQuery中捕获数组的内容。

$( document ).ready( function(){
  
  $.ajax({ 
      
       url : 'get.php',
    
       type : 'get',
       
       dataType : 'json'
  
    }).done( function( data1, data2 ){
     
     $( 'span:nth-last-child(2)' ).text(data1);
    
     $( 'span:nth-last-child(1)' ).text(data2);
    
    });
  
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  
  <span></span>
  
  <span></span>
  
</div>

<?php

  $val1 = [ "red", "green", "blue" ];

  $val2 = [ "apple", "mango" , "orange" ];

  echo json_encode( $val1 );

  echo json_encode( $val2 );

?>

必填结果

red,green,blue
apple,mango,orange

3 个答案:

答案 0 :(得分:2)

最好将两个数组添加到一个数组数组中,然后将其作为json编码的字符串发送回来,稍后可以从jQuery解码:

<?php 
$arr = [0=>$val1, 1=>$val2];
//Send encoded string to client
echo json_encode($arr);
//This will produce something like: [["red","green","blue"],["apple","mango","orange"]]
?>

答案 1 :(得分:1)

更改get.php

<?php

  $data['val1'] = [ "red", "green", "blue" ];

  $data['val2'] = [ "apple", "mango" , "orange" ];

  echo json_encode( $data );

?>

更改脚本

$( document ).ready( function(){

  $.ajax({ 

       url : 'get.php',

       type : 'get',

       dataType : 'json'

    }).done( function( data ){

     $( 'span:nth-last-child(2)' ).text(data.val1);

     $( 'span:nth-last-child(1)' ).text(data.val2);

    });

  });

答案 2 :(得分:1)

<?php

  $val1 = [ "red", "green", "blue" ];

  $val2 = [ "apple", "mango" , "orange" ];

  echo json_encode(['val1'=>$val1,'val2'=>$val2]);

?>

然后在jquery

.done( function(response){
     var res = json_decode(response);
     $( 'span:nth-last-child(2)' ).text(res.val1);

     $( 'span:nth-last-child(1)' ).text(res.val2);

    });