[英]ajax get json function doesn't work
我想从一个 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 );
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.