简体   繁体   中英

Use jQuery ajax call PHP with json return and try to build a list from the json object

I am using the following code to call PHP to get json back and trying to parse the json object returned and make a list of hyperlinks. I got json object back from PHP but my list was empty. Please help! Here is my jQuery code and json return

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);

} 

And my json return from PHP is

[ {"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 is async that's why its not working because you appending empty html before fetching json data. append your html inside success callback of $.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);
       });


    }

you don't have to use $.each and oh! you have to append your HTML inside the AJAX call

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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