jquery中的函数返回undefined

我在jquery中调用的函数返回undefined。 我检查了这个函数,当我发现它时它返回了正确的数据。

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

您通过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; } 

addToPlaylist函数不return任何内容。 它产生一个异步请求,最终执行一个返回函数的回调函数。 原始的addToPlaylist函数很久就完成了,并且在发生这种情况时返回,并且回调函数返回到nobody。

success: function(msg) { }代码在不同的上下文中执行,并且晚于周围的addToPlaylist函数。

试试这个看看它的实际效果:

 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 } 

我同意deceze。 您需要做的是在success函数中为rendered_item执行必要的操作,而不是依赖于从addToPlayList()获取一些东西。