$ .getJSON返回/作用域问题? [英] $.getJSON return/scope issue?

查看:109
本文介绍了$ .getJSON返回/作用域问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,警报始终在项目中显示空值

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

我希望返回HTML(字符串格式),以便可以在$(#").after(item)中使用它.

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

推荐答案

$.getJSON()异步返回结果. return $.getJSON()从函数,使用.then()链接到函数调用,包括.fail()链接到.then()来处理$.getJSON()返回的可能错误.

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

这篇关于$ .getJSON返回/作用域问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆