2013-10-08 24 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());

相关问题