我正在摸索如何结合2个jQuery ajax调用的结果,这些调用将结果返回到相同的DOM元素中。这是我的设置:
问题:这两个电话各自正常工作。但问题是,一次调用的结果总是替换第二次调用的结果,反之亦然。
var postUrl = "http://localhost:8000/ingredients/";
var ingrUrl = "http://localhost:8000/ingrs/";
var selectedFoods = [];
var selectedIngrs = [];
$('.foods a').click(function(event){
clickedLink = $(this).attr('id');
if (selectedFoods.indexOf(clickedLink) != -1) {
var index = selectedFoods.indexOf(clickedLink);
selectedFoods.splice(index, 1);}
else {
selectedFoods.push(clickedLink);
};
var jsonFoods = JSON.stringify(selectedFoods);
$.ajax({
url: postUrl,
type: 'POST',
data: jsonFoods,
dataType: 'html',
success: function(result){
$('.ingredients').html(result);
}
});
});
$('.ingr-list a').click(function(event) {
clickedIngr = $(this).attr('id');
if (selectedIngrs.indexOf(clickedIngr) != -1) {
var index = selectedIngrs.indexOf(clickedIngr);
selectedIngrs.splice(index, 1);}
else {
selectedIngrs.push(clickedIngr);
};
var jsonIngrs = JSON.stringify(selectedIngrs);
$.ajax({
url: ingrUrl,
type: 'POST',
data: jsonIngrs,
dataType: 'html',
success: function(result){
$('.ingredients').html(result);
}
});
});
我尝试使用$('.ingredients').html(result);
代替append
使用此行html
,但这不起作用,因为用户应该可以从列表中取出成分(请参阅如果两个函数都有条件的话。)
答案 0 :(得分:3)
只需为他们使用不同的容器
<div class="ingredients">
<div id="first"></div>
<div id="second"></diV>
</div>
然后设置.html()
和$("#first")
的{{1}}而不是$("#second")
答案 1 :(得分:0)
使用.append
$('.ingredients').append(result);
答案 2 :(得分:0)
看看这是答案underscore js template
你需要做的不是传回html,而是传回 json ,并使用js模板在浏览器中渲染它。
一些假代码:
var global_ingredients = [];
var list = "<% _.each(ingredients, function(ingredient) \
{ %> <li><%= ingredient.name %></li> <% }); %>;";
$.post('', postdata, function(ingredients){
global_ingredients.push(ingredients);
// here you could also eliminate duplicated ingredients,
// sort the ingredients, do whatever you likes
var new_html = _.template(list, global_ingredients);
$('.ingredients').html(new_html);
});