$.getJSON return/scope issue? [duplicate]

2019-09-08 12:45发布

问题:

This question already has an answer here:

  • How do I return the response from an asynchronous call? 35 answers
  • Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference 6 answers

This is my code and the alert always displaying null as value in item

    function make_recent_item(recent_counter){
    var json_path_popular= 'http://localhost/complaints_old/webservice/get_new_complaints' + '?recent_counter='+recent_counter;
    var item=null;
    $.getJSON( json_path_popular, function( data ){
      item=
        '<div class="item list">'+
              '<div class="image">'+
                  '<div class="quick-view" '+data.data[0].complaint_id+'><i class="fa fa-eye"></i><span>Quick View</span></div>'+
                  '<div href="item-detail.html">'+
                      '<img style="width:260px;height:195px;" src="data:image/jpg;base64,'+ data.data[0].picture +  '"/>'+
                  '</div>'+
              '</div>'+
              '<div class="wrapper">'+
                  '<a href="item-detail.html"><h3>Cash Cow Restaurante</h3></a>'+
                  '<figure>'+data.data[0].municipality_name+'</figure>'+
                  '<div class="info">'+
                  '</div>'+
              '</div>'+
          '</div>';
     });
     alert(item);
     return item;
}

I want the HTML (in string format) to be returned so I can use it in $("#").after(item).

回答1:

$.getJSON() returns results asynchronously. return $.getJSON() from function, use .then() chained to function call, include .fail() chained to .then() to handle possible error returned by $.getJSON().

 function make_recent_item(recent_counter) {
   var json_path_popular= 'http://localhost/complaints_old/webservice/get_new_complaints' + '?recent_counter='+recent_counter;
   return $.getJSON(json_path_popular)
 }

 make_recent_item(/* parameter */)
 .then(function( data ){
   var item ='<div class="item list">'+
           '<div class="image">'+
              '<div class="quick-view" '+data.data[0].complaint_id+'><i class="fa fa-eye"></i><span>Quick View</span></div>'+
              '<div href="item-detail.html">'+
                  '<img style="width:260px;height:195px;" src="data:image/jpg;base64,'+ data.data[0].picture +  '"/>'+
              '</div>'+
          '</div>'+
          '<div class="wrapper">'+
              '<a href="item-detail.html"><h3>Cash Cow Restaurante</h3></a>'+
              '<figure>'+data.data[0].municipality_name+'</figure>'+
              '<div class="info">'+
              '</div>'+
          '</div>'+ 
      '</div>';
      // do stuff with `item`
      $(item).appendTo("body");
 })
 .fail(function(jqxhr, textStatus, errorThrown) {
   console.log(textStatus, errorThrown);
 });