[英]how to get two or more array data from php page to javascript using json
下面的代碼在EAddEmployeeAddAndOtherParts.php
頁面中:
$array1 = array("i am first array");
$array2 = array("i am second array");
echo json_encode($array1,$array2);
下面的代碼在home.html
頁面中:
$(document).ready( function() {
$.ajax({
type: 'POST',
url: 'EAddEmployeeAddAndOtherParts.php',
data: 'aa='+aa+'&f='+f,
dataType: 'html',
cache: false,
success: function(result1,result2) {
alert(result1[0]);
alert(result2[0]);
},
});
});
我的問題是:如何使用JSON在home.html
頁面中獲取$array1
和$array2
數據? 我上面的代碼無法正常工作。
json_encode()
僅將第一個參數用作數據,因此將您的兩個數組包裝為一個數組:
echo json_encode(array('array1' => $array1, 'array2' => $array2));
在ajax調用中,響應是第一個參數,由於在上面我們使用了鍵,因此可以直接引用result.array1
。 所以改為
dataType: 'json',
success: function(result) {
alert(result.array1);
alert(result.array2);
},
還要注意,我將dataType更改為json
。 如果您繼續使用html
作為dataType,那么jQuery不會自動為您解析JSON。
header('Content-type:application/json');
echo json_encode(array($array1,$array2));
exit;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.