[英]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.