我无法通过函数调用多个ajax请求来设置标记变量。函数的数量将不知道,但是对于这个例子,我做了2并将它们放在相同的js文件中。我试图循环使用未知数量的函数,并在响应中附加一个标记变量。
然而,在函数结束之前,ajax请求没有完成。我怎样才能确保在继续之前从ajax得到回复?
getMarkup()将在document.ready
上运行function getMarkup(){
var news = [];
news.push('loadnews1');
news.push('loadnews2');
len = news.length;
var markup;
for(i=0; i<len; i++){
try{
markup = eval(news[i] + '();');
}catch(ex){
}
}
console.log(markup);
}
function loadnews1(){
var host = 'http://test.com';
var path = '/ajax-feeds/news/json1';
var markup = "";
$.ajax({
url: host + path,
dataType: "json",
async: true,
success: function(data) {
$.each( data, function( key, value ) {
markup += '<div id="new-row-'+key+'" class="news-row">' +
'<div class="news-row-spotlight-image"><img src="'+value.picture+'"></div>' +
'<div class="news-row-spotlight-title">'+value.title+'</div>' +
'<div class="news-row-title">'+value.subtitle+'</div>' +
'<div class="news-row-spotlight-teaser">'+value.body+'</div>' +
'<div class="news-row-spotlight-link"><a href="http://test.com/'+value.nid+'">More Link</a></div></div>';
});
return markup;
}
});
}
function loadnews2(){
var host = 'http://test.com';
var path = '/ajax-feeds/news/json2';
var markup = "";
$.ajax({
url: host + path,
dataType: "json",
async: true,
success: function(data) {
$.each( data, function( key, value ) {
markup += '<div id="new-row-'+key+'" class="news-row">' +
'<div class="news-row-spotlight-image"><img src="'+value.picture+'"></div>' +
'<div class="news-row-spotlight-title">'+value.title+'</div>' +
'<div class="news-row-title">'+value.subtitle+'</div>' +
'<div class="news-row-spotlight-teaser">'+value.body+'</div>' +
'<div class="news-row-spotlight-link"><a href="http://test.com/'+value.nid+'">More Link</a></div></div>';
});
return markup;
}
});
}