$ .getJson> $ .each返回undefined

时间:2010-03-17 20:02:51

标签: jquery

function getData(d){
Back = new Object();

$.getJSON('../do.php?',
   function(response){    
    if(response.type == 'success'){ 
    Back = { "type" : "success", "content" : "" };
    $.each(response.data, function(data){   
       Back.content +='<div class="article"><h5>'+data.title+'</h5>'
       Back.content +='<div class="article-content">'+data.content+'</div></div>';
      });

    }
    else{
     Back = {"type" : "error" };
    }

    return Back;
  });
}

console.log(getData()); 

返回undefined!为什么呢?

2 个答案:

答案 0 :(得分:2)

您无法以同步方式调用异步函数。在您的代码中,这个:

function(response){    
    if(response.type == 'success'){ 
    Back = { "type" : "success", "content" : "" };
    $.each(response.data, function(data){   
       Back.content +='<div class="article"><h5>'+data.title+'</h5>'
       Back.content +='<div class="article-content">'+data.content+'</div></div>';
      });

    }
    else{
     Back = {"type" : "error" };
    }    
    return Back;
}

在此之后运行:console.log(getData());

一旦服务器返回响应,$.getJSON中的回调(第二个参数)就会运行,这不会立即发生。

如果您在实际运行时调用日志记录,您将获得预期的结果:

Back = new Object();
$.getJSON('../do.php?', function(response) {    
  if(response.type == 'success') { 
    Back = { "type" : "success", "content" : "" };
    $.each(response.data, function(data) {   
      Back.content +='<div class="article"><h5>'+data.title+'</h5>';
      Back.content +='<div class="article-content">'+data.content+'</div></div>';
    });
  } else {
    Back = {"type" : "error" };
  }
  console.log(Back); 
});

答案 1 :(得分:0)

Back = new Object();

$.ajax({
    type: "GET",
    async: false,
    url: "../do.php",
    dataType: 'json',
    success: function(response){
        if(response.type == 'success'){ 
            Back = { "type" : "success", "content" : "" };
            $.each(response.data, function(data){           
                        Back.content +='<div class="article"><h5>'+data.title+'</h5><div class="article-image"><img src="'+data.image+'" alt="article_image" /></div>'
                        Back.content +='<div class="article-content">'+data.content+'</div><br class="clear" /></div><!-- /article -->';
                    });

            }
            else{
                Back = {"type" : "error" };
            }

            return Back;
    }});

它应该像这样工作吗?