$ .getJson> $ .each返回未定义 [英] $.getJson> $.each returns undefined

查看:118
本文介绍了$ .getJson> $ .each返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

返回未定义!为什么?

推荐答案

您不能以同步方式调用异步函数.在您的代码中,这是

You can't call an asynchronous function in a synchronous way. In your code, this:

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中的回调(第二个参数)在服务器返回响应后立即运行,但不会立即发生.

The callback (second parameter) in $.getJSON runs once the server returns a response, this doesn't happen instantly.

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

If you call the logging when it actually runs like this, you will get the expected results:

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

这篇关于$ .getJson&gt; $ .each返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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