当函数与JQuery一起使用时,Ajax响应具有不同的格式

我正在练习JQuery .when()函数,当我使用.when执行ajax调用的两个函数时,我收到了意想不到的结果。

例如,对于单一function

$.when(getFolders(id)).then(function(folders) { /* return value is as expected */ }); 

以下是本案例中文件夹的内容,

在此处输入图像描述

但是,在以下情况中,

 $.when(getFolders(idOfClickedFolder), getFiles(idOfClickedFolder)) .then(function( folders, files ) { /* results formats are not similar here with above one */ }); 

文件夹的内容如下所示,实际的Folder对象位于第一个响应对象内。 我的意思是我可以通过文件夹[0]访问返回的JSON对象。

在此处输入图像描述

以下是getFolders函数,getFiles与getFolders相同,具有不同的ajax url。

 function getFolders(rootId) { return $.ajax({ url: '/FileManager/GetFolders/' + rootId, async: true, dataType: 'json' }); } 

我想知道为什么我得到两种不同格式的结果。

谢谢。

jQuery AJAX Deferred总是返回3个参数:data,textStatus,jqXHR。 从服务器返回的数据,根据dataType参数格式化; 描述状态的字符串; 和jqXHR(在jQuery 1.4.x,XMLHttpRequest)对象。 (来自$ .ajax doc http://api.jquery.com/jQuery.ajax/

当你使用带有2个AJAX deffered的$ .when时,这3个参数都在一个数组中。

来自$ .when()doc: http : //api.jquery.com/jQuery.when/

 $.when( $.ajax("test.aspx") ).then(function(ajaxArgs){ alert(ajaxArgs[1]); /* ajaxArgs is [ "success", statusText, jqXHR ] */ }); 

如果要创建自定义AJAX延迟仅返回第一个参数,则可以执行以下操作:

 // creating a new deferred var myDfd = $.Deferred(); // execute AJAX query, and when the query is okay, resolve my deferred with only the res of the AJAX query $.ajax({ url: '/FileManager/GetFolders/' + rootId, async: true, dataType: 'json' }).then(function(folders) { myDfd.resolve(folders); }); // I can use my own Deferred $.when(myDfd).then(function(folders) { // folders contains ajax response only });