$ .getJSON返回/范围问题?

时间:2017-04-29 02:10:18

标签: javascript jquery getjson

这是我的代码,警告始终在项目

中显示为null
    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;
}

我希望返回HTML(字符串格式),以便我可以在$(&#34;#&#34;)。(item)之后使用它。

1 个答案:

答案 0 :(得分:0)

$.getJSON()异步返回结果。来自函数的return $.getJSON(),使用链接到函数调用的.then(),将.fail()链接到.then()以处理$.getJSON()返回的可能错误。< / p>

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