2016-12-28 44 views
0

是否有可能從php發送兩個不同的數組到jQuery?嘗試從php中獲取兩個不同的數組,以獲取兩個不同的回調參數,捕獲jQuery中數組的內容。爲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 
+1

您返回數組'回聲json_encode(陣列($ val1,$ val2));' – Satpal

回答

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); 

    }); 

    }); 
+0

@YSuraj:提供了答案 –

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
<?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); 

    });