Ajax响应与JQuery的功能时,使用时不同的格式不同、功能、格式、Ajax

2023-09-11 01:33:49 作者:该账号已被封号

我在练与jQuery。当()函数,我收到意想不到的效果,当我使用。当有2个功能执行Ajax调用。

I am practicing with JQuery .when() function and I receive unexpected results when I use .when with 2 functions that performs ajax calls.

例如,对于单一功能

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

以下是夹在这种情况下的内容,

Following is the content of folders in this case ,

但是,在以下情况下,

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

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

content of folders is like below, an the actual Folder objects are located inside the first Object of response. I mean I can access the returned JSON object via folders[0].

以下是getFolders功能,GetFiles的是同具有不同的URL的AJAX getFolders。

Following is the getFolders function, getFiles is same as getFolders having different url for ajax.

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

我想知道为什么我收到的结果有两种格式。

I am wondering why I am getting the results in two different format.

感谢。

推荐答案

一个jQuery的AJAX总是推迟返回3个参数:数据,textStatus,jqXHR。根据dataType参数从服务器返回的数据,格式化的;描述状态的字符串;和jqXHR(jQuery的1.4.x的,XMLHtt prequest)对象。 (由$就DOC http://api.jquery.com/jQuery.ajax/ )

A jQuery AJAX Deferred always returns 3 arguments : data, textStatus, jqXHR. The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. (from $.ajax doc http://api.jquery.com/jQuery.ajax/ )

当您使用$。当有2 AJAX deffereds,这3个参数是一个数组中。

When you use $.when with 2 AJAX deffereds, these 3 arguments are in an array.

从$。当()DOC: http://api.jquery.com/jQuery。当/

From the $.when() doc : http://api.jquery.com/jQuery.when/

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

如果你想创建递延只返回第一个参数的自定义AJAX,你可以这样做:

If you want to create a custom AJAX Deferred returning only first argument, you can do :

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