[英]How to return a json object from a function in jquery with no ajax call?
[英]Use jQuery ajax call PHP with json return and try to build a list from the json object
我正在使用以下代碼來調用PHP以取回json,並嘗試解析返回的json對象並創建超鏈接列表。 我從PHP返回了json對象,但列表為空。 請幫忙! 這是我的jQuery代碼和json返回
html code
<div id="document_list"></div>
function GetDocListMain() {
var html='';
$.getJSON("getUserDocument.php?id=" + <?php echo $_GET["id"] ?>,
function(data){
alert(data);
$.each(data, function(index, item){
html +='<li><a href="download_doc.php?id=' + item.id +'">' + item.file_name + ' | ' + item.created + '</a></li>' ;
});
});
$('#document_list').empty();
$('#document_list').append(html);
}
我從PHP返回的json是
[ {"id":"1", "file_name":"testfile1.pdf", "created":"2017-02-11"},
{"id":"2", "file_name":"testfile2.pdf", "created":"2016-11-12"},
{"id":"3", "file_name":"testfile6.pdf", "created":"2016-10-12"}
]
$.getJSON
是異步的,這就是為什么它不起作用的原因,因為在獲取json數據之前附加了空的html。 將您的html附加到$.getJSON
成功回調中
function GetDocListMain() {
var html='';
$.getJSON("getUserDocument.php?id=" + <?php echo $_GET["id"] ?>,
function(data){
$.each(data, function(index, item){
html +='<li><a href="download_doc.php?id=' + item.id +'">' + item.file_name + ' | ' + item.created + '</a></li>' ;
});
$('#document_list').empty();
$('#document_list').append(html);
});
}
您不必使用$ .each和哦! 您必須將HTML附加到AJAX調用中
function GetDocsListMain(){
var html='';
$.getJSON("getUserDocument.php?id=" + <?php echo $_GET["id"] ?>,
function(data){
alert(data);
for(var i = 0; i < data.length; i++){
html +='<li><a href="download_doc.php?id=' + data[i].id +'">' + data[i].file_name + ' | ' + data[i].created + '</a></li>' ;
}
$('#document_list').empty();
$('#document_list').append(html);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.