2016-04-20 67 views
-1

我想從php頁面獲取json文件,但是我的代碼不工作,出了什麼問題?ajax get json函數不起作用

my php page is

header('Content-type: application/json'); 
$jsonstart="{'files' : ["; 
$jsonend="]}"; 
$content="{'firstname' : '".$_GET['name']."' , 'lastname' : 'izadi'}"; 
$jsonfile=$jsonstart.$content.$jsonend; 
print $jsonfile; 

my ajax code is

$(document).ready(function(){ 
    $.getJSON("getfilesinfo.php?name=afshin", function(data){ 
     alert(); 
     var test=JSON.parse(data); 
     alert("Data: " + test.files[1].firstname + "\nStatus: " + status); 
    }); 
}); 
+1

必須用'json_encode(ARRAY)' – Rayon

+0

做,如果你安慰的數據,你會得到什麼,即'控制檯。日誌(數據);'在getJSON()回調? –

+1

'$ jsonfile'不是有效的'JSON' – Rayon

回答

1

你必須在你的PHP文件中像這樣使用json_encode()。

<?php 
header('Content-type: application/json'); 

$array = array(
    'firstname' => $_GET['name'], 
    'lastname' => 'izadi' 
); 

echo json_encode($array); 

exit; 
0

使用json_encode

<?php 
header('Content-type: application/json'); 

$array = array(
    'firstname' => $_GET['name'], 
    'lastname' => 'izadi' 
); 

echo json_encode(array('files'=>array($array))); 

JS試試這個乾淨的代碼:

$(document).ready(function(){ 
    $.getJSON("getfilesinfo.php?name=afshin", function(test){ 
     alert("Data: " + test.files[1].firstname); 
    }); 
});