2017-01-09 36 views
0

我是新來的JS和我的新項目有選擇2,在目前,我有這樣的代碼(這是一個有點簡化版本),它工作得很好:過濾AJAX響應與其他AJAX請求

$("#group-search").select2({ 
    ajax: { 
     url: "groups.search", 
     dataType: 'jsonp', 
     data: function (term, page) { 
     return { 
      q: term, 
      access_token: access_token 
     }; 
     }, 
     results: function (data, page) { 
     return { results: data.response.items }; 
     } 
    } 
    }); 

但我需要在另一個AJAX請求的幫助下過濾我的結果(data.response.items)。是否有可能實現?

更新1

這就是我試圖根據ValLenain 建議這樣做,但它不工作:

results: function (data, page) { 
    var groups = data.response.items; 

    var groupIds = new Array; 
    groups.forEach(function (group) { 
     groupIds.push(group.id); 
    }); 

    $.ajax({ 
     url: "groups.getById", 
     dataType: 'jsonp', 
     data: { 
     group_ids: groupIds, 
     v: '5.60', 
     access_token: access_token 
     }, 
     success: function(data, page) { 
     return { results: data.response }; 
     } 
    }).then(function(response){ 
     groups = []; 
// so at this moment we are expecting the select field to become empty, right? 
// it doesn't work that way, nothing changes 
    }); 

    return { results: groups }; 
    } 

回答

0

我從來沒有嘗試過,但改變你的results功能如果您首先返回一個空數組並在ajax調用中進行更新,則可以使用ajax調用。

results: function (data, page) { 
    var items = []; 

    /* Since I don't know what your ajax call is nor 
    * what it takes as arguments or returns, I just write 
    * a fake one. 
    */ 
    ajaxCall(data.response.items).then(function(filteredItems) { 
    /* update here the items array 
    * it's important to change the existing object, not 
    * to create a new one 
    */ 
    }); 
    return { results:items }; 
} 

關於你提到的更新1

你改變由groups變量,所以引用的對象,您之前返回(data.response.items)不會得到更新。

我已經重寫功能

/* Set groups to an empty array so the select2 
* component will never display unfiltered value. 
*/ 
var groups = []; 

var groupIds = new Array; 
data.response.items.forEach(function (group) { 
    groupIds.push(group.id); 
}); 

$.ajax({ 
     url: "groups.getById", 
     dataType: 'jsonp', 
     data: { 
     group_ids: groupIds, 
     v: '5.60', 
     access_token: access_token 
     }, 
     success: function(data, page) { 
     /* Here I assume your items are in data.response.items. 
     * We push all the items into the existing array, without 
     * creating a new array (so we keep the reference). 
     */ 
     Array.prototype.push.apply(groups, data.response.items); 

     /* The return statement is optional here */ 
     return { results: data.response }; 
     } 
    }); 

    return { 
    results: groups 
    } 
+0

@VaIleNain的身體,但不會對'{返回結果:項目};'語句中的'函數(filteredItems)'解僱之前很長一段時間?這不是AJAX調用的重點嗎?或者我在這裏錯過了什麼? –

+0

@VaILeNain,我剛剛嘗試過,它按照我的預期工作。 'return {results:items};'在過濾ajax調用之前觸發。如果你需要完整的代碼,我可以更新我的主文章 –

+0

是的,return語句將在第二次ajax調用之前很長時間執行,但它返回的對象(例如'{results:items}')將在ajax調用後更新因爲我們保留對它的引用。 – ValLeNain