2013-10-08 26 views
0

我有一個通過get json函數添加數據元素的腳本。如何確保在get函數完全完成並呈現後運行其他函數?

$(document).ready(function() { 
     ADD.Listitem.get(); 
     }); 

它basicly增加了數據的一串HTML標籤等。我的問題是以下幾點:

$(document).ready(function() { 
    ADD.Listitem.get(); 

    var arr = []; 
    $(".Listitem-section-item-title").each(function() { 
     arr.push($(this.text())); 
    }); 
}); 

-

get: function(web) { 
      AST.Utils.JSON.get("/_vti_bin/AST/ListItem/ListitemService.svc/GetListItem", null, AST.Listitem.renderListitem); 
     }, 
renderListitem: function(data) { 
      $("#Listitem-template").tmpl(data["ListItemResults"]).prependTo(".ListItem-section-template"); 
    } 

這裏是JSON得到:

ADD.Utils.JSON.get = function (url, data, onSuccess) { 
    $.ajax({ 
     type: "GET", 
     contentType: "application/json; charset=utf-8", 
     async: true, 
     url: url, 
     data: data, 
     cache: false, 
     dataType: "json", 
     success: onSuccess, 
     error: ADD.Utils.JSON.error, 
     converters: { "text json": ADD.Utils.JSON.deserialize } 
    }); 
} 

數組每個循環不是ru因爲get方法沒有完成呈現Listitem-section-item-title選擇器,所以它不能找到選擇器。

有沒有什麼好的解決方案呢?

+3

如果'get()'是異步的(它看起來像),它應該接受一個回調參數或返回一個承諾。你是這個功能的作者嗎? –

+1

你的意思是'get'是異步的嗎?然後,它可能接受回調或返回一個承諾* [編輯:該死的,弗雷德裏克更快......至少它是可見的我同意:)] *。 –

+0

您可以將Ajax代碼放入$(document).ready()函數中,然後將額外的代碼放入Ajax調用的Success函數中。 – Nunners

回答

1

你可以改變你的函數返回由$.ajax給出的承諾:

ADD.Utils.JSON.get = function (url, data) { 
    return $.ajax({ 
     type: "GET", 
     contentType: "application/json; charset=utf-8", 
     async: true, 
     url: url, 
     data: data, 
     cache: false, 
     dataType: "json", 
     converters: { "text json": ADD.Utils.JSON.deserialize } 
    }).fail(ADD.Utils.JSON.error); 
} 

get: function(web) { 
    return AST.Utils.JSON.get("/_vti_bin/AST/ListItem/ListitemService.svc/GetListItem", null).done(AST.Listitem.renderListitem); 
}, 

所以,你可以做

$(document).ready(function() { 
    ADD.Listitems.get().done(function(){ 
     var arr = []; 
     $(".Listitem-section-item-title").each(function() { 
      arr.push($(this.text())); 
     }); 
    }); 
}); 
+0

我收到「無法調用方法'完成'undefined:S – Obsivus

+0

你知道爲什麼嗎? – Obsivus

+0

有兩個函數需要修改以返回諾言。 'ADD.Utils.JSON.get')和你的'ADD.Listitem.get'(我作爲一個練習) –

0

回調:

$(document).ready(function() { 
ADD.Listitem.get(url,data,function(){ 
    var arr = []; 
    $(".Listitem-section-item-title").each(function() { 
    arr.push($(this.text())); 
    }); 
}); 
}); 

沒有回調:

如果你不能得到get方法採取回調或返回一個承諾那麼我認爲最好的辦法將是檢查的時候完成。

$(document).ready(function() { 

    ADD.Listitem.get(); 

    var timer = setInterval(function(){ 
    if ($("#thingWhichShouldExist").length>0){ 
     var arr = []; 
     $(".Listitem-section-item-title").each(function() { 
     arr.push($(this.text())); 
     }); 
    clearInterval(timer); 
    } 
    },50); 
}); 
-1

檢索值和成功,調用一個函數將把值推入數組中。

另外,arr.push($(this.text()));應該是arr.push($(this).text());

相關問題