简体   繁体   English

ajax 获取 json 函数不起作用

[英]ajax get json function doesn't work

i wanna to get a json file from a php page but my code doesn't work, what's wrong?我想从一个 php 页面获取一个 json 文件,但我的代码不起作用,怎么了?

my php page is我的 php 页面是

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

my ajax code is我的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);
     });  
});

You must use json_encode() in your php file like this.您必须像这样在 php 文件中使用 json_encode() 。

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

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

echo json_encode($array);

exit;

try this cleaner code using json_encode使用 json_encode 试试这个更简洁的代码

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

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

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

js: js:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM