我在jquery内部调用的函数返回undefined。我检查了这个函数,当我对它进行firebugged时,它返回了正确的数据。
function addToPlaylist(component_type,add_to_pl_value,pl_list_no)
{
add_to_pl_value_split = add_to_pl_value.split(":");
$.ajax({
type: "POST",
url: "ds/index.php/playlist/check_folder",
data: "component_type="+component_type+"&value="+add_to_pl_value_split[1],
success: function(msg)
{
if(msg == 'not_folder')
{
if(component_type == 'video')
{
rendered_item = render_list_item_video(add_to_pl_value_split[0],add_to_pl_value_split[1],pl_list_no)
}
else if(component_type == 'image')
{
rendered_item = render_list_item_image(add_to_pl_value_split[0],add_to_pl_value_split[1],pl_list_no)
}
}
else
{
//List files from folder
folder_name = add_to_pl_value_split[1].replace(' ','-');
var x = msg; // json
eval('var file='+x);
var rendered_item;
for ( var i in file )
{
//console.log(file[i]);
if(component_type == 'video')
{
rendered_item = render_list_item_video(folder_name+'-'+i,file[i],pl_list_no) + rendered_item;
}
if(component_type == 'image')
{
rendered_item = render_list_item_image(folder_name+'-'+i,file[i],pl_list_no) + rendered_item;
}
}
}
$("#files").html(filebrowser_list); //Reload Playlist
console.log(rendered_item);
return rendered_item;
},
error: function()
{
alert("An error occured while updating. Try again in a while");
}
})
}
$('document').ready(function()
{
addToPlaylist($('#component_type').val(),ui_item,0); //This one returns undefined
});
发布于 2010-03-24 10:32:02
您通过AJAX发出请求,根据定义,AJAX是异步的。这意味着您将在AJAX请求完成之前从函数返回。实际上,返回语句是没有意义的,因为它是从回调函数返回的,而不是从addToPlaylist
函数返回的。
你有几个选择。第一个更好。
首先,您可以利用AJAX请求的异步特性,将回调传递到addToPlaylist
方法中(非常类似于将匿名回调传递给ajax函数),并使用AJAX回调,调用该函数而不是进行返回。这样,您的请求将异步完成,并且在运行时不会锁定您的浏览器。
function addToPlaylist(component_type, add_to_pl_value, pl_list_no, cb )
{
...yada yada yada...
$.ajax({
...
success: function(data) {
...
if (cb) {
cb.apply(this, rendered_item );
}
}
});
}
其次,可以将选项aSync: false
添加到ajax调用中。这将强制AJAX调用同步运行(本质上它只是循环,直到调用返回,然后调用您的回调)。如果这样做,您需要在回调内的addToPlaylist
函数中捕获一个局部变量,并从回调中将值赋给它。在addToPlaylist
函数的末尾,返回此变量作为结果。
function addToPlaylist(component_type, add_to_pl_value, pl_list_no )
{
...yada yada yada...
var result = null;
$.ajax({
aSync: false,
...
success: function(data) {
...
result = rendered_item;
}
});
return rendered_item;
}
发布于 2010-03-24 10:25:36
函数addToPlaylist
不会return
任何东西。它发出一个异步请求,该请求最终执行一个回调函数,该函数返回一些内容。原来的addToPlaylist
函数已经完成很长时间了,并在发生这种情况时返回,而且回调函数没有返回给任何人。
即,与周围的addToPlaylist
函数相比,success: function(msg) { }
代码在不同的上下文中并且在较晚的时间执行。
尝试这样做可以看到它的实际效果:
function addToPlaylist() {
$.ajax({
...
success : function () {
alert('second'); // comes after 'first'
return null; // returns to nobody in particular
}
});
alert('first'); // comes before 'second'
return 'something'; // can only return here to caller
}
发布于 2010-03-24 10:31:47
我同意deceze的观点。您需要做的是在success函数中为rendered_item执行必要的操作,而不是依赖于从addToPlayList()获取某些东西。
https://stackoverflow.com/questions/2504950
复制相似问题