结合2个jQuery ajax调用的结果

时间:2012-07-02 07:12:22

标签: javascript jquery ajax

我正在摸索如何结合2个jQuery ajax调用的结果,这些调用将结果返回到相同的DOM元素中。这是我的设置:

  • 有2个电话:一个来自食物清单,第二个来自成分列表
  • 两个电话都会返回成分列表
  • 想法是根据2个来源(食物清单和成分清单)制作购物清单(购买食材)​​
  • 用户可以通过选择食物(从数据库中检索成分)创建购物清单,也可以直接从成分列表中选择成分

问题:这两个电话各自正常工作。但问题是,一次调用的结果总是替换第二次调用的结果,反之亦然。

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,但这不起作用,因为用户应该可以从列表中取出成分(请参阅如果两个函数都有条件的话。)

3 个答案:

答案 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);
});