我有一个JS函数,调用它是为了获取特定月份的帖子标题列表。数据以JSON对象的形式返回。我希望将数据返回给调用函数。响应的形式如下:
{
"success":true,
"days":[
{
"date":"2,March 2013",
"posts":[
{
"post_id":"10",
"post_title":"tgfkyhhj",
"created_on":"2013-03-02 21:24:17",
"time":"09:24 PM"
}
]
}
]
}
我希望退还这个JSON的一部分。
函数如下:
function archivePostMonth(month) {
var days;
$.ajax({
'type' : 'get',
'url' : base_url + 'index.php/blog/blogArchiveMonth',
'data' : {
'blogId' : blogId,
'month' : month,
},
success : function(response) {
var res = jQuery.parseJSON(response);
if (res.success == true) {
console.log(res.days); //displays the data
days = res.days;
console.log(days); // displays the data
}
}
});
console.log(days); //undefined
return days; // returns undefined
}
无论函数返回什么,都是undefined。我找不出问题所在。有没有更好的方法来做这件事?
发布于 2013-03-12 11:49:57
ajax是异步的,因此,在您的代码中,您正在执行对服务器的请求,同时返回days的值(一个值未定义的变量)。
在调用成功回调之前,变量days没有值,这发生在函数已经返回undefined之后。
https://stackoverflow.com/questions/15360319
复制