ajax get-json函数没有'不起作用

ajax get json function doesn't work

本文关键字:不起作用 get-json 函数 ajax      更新时间:2023-09-26

我想从php页面获得一个json文件,但我的代码不起作用,怎么了?

我的php页面是

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

我的ajax代码是

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

您必须像这样在php文件中使用json_encode()。

<?php
header('Content-type: application/json');
$array = array(
    'firstname' => $_GET['name'],
    'lastname' => 'izadi'
);
echo json_encode($array);
exit;

使用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 );
     });  
});