【问题标题】:AJAX - Double Results on Page RefreshAJAX - 页面刷新双倍结果
【发布时间】:2012-02-19 16:20:03
【问题描述】:

我有这段代码,它使用 AJAX 显示来自 XML 提要的一些位置:

$.ajax({
    type: "GET",
    url: "testxml.xml",
    dataType: "xml",
    success: function(xml) {
        $(xml).find("Country[Name='"+localStorage.ArrivalCountry+"']").find('Destination').each(function(){
            var destinationName = $(this).attr('Name');
            $('<a class="listItem" href="#" id="'+destinationName+'">'+destinationName+x+'<div class="arrow"></div></a>').appendTo('#destinationList');
        });

    }
});

第一次正确显示,但如果我刷新页面,它会显示每个结果两次。如果我再做一次,它会显示三遍,依此类推。

【问题讨论】:

  • 您的 Ajax 调用返回什么???给我们举个例子..

标签: javascript jquery xml ajax


【解决方案1】:

在添加更新集之前,您需要从#destinationList 中获取empty() 之前的 AJAX 调用数据:

$.ajax({
    type: "GET",
    url: "testxml.xml",
    dataType: "xml",
    success: function(xml) {
        $("#destinationList").empty(); // This will clear out all the previously appended 'a' elements
        $(xml).find("Country[Name='"+localStorage.ArrivalCountry+"']").find('Destination').each(function() {
            var destinationName = $(this).attr('Name');
            $('<a class="listItem" href="#" id="'+destinationName+'">'+destinationName+x+'<div class="arrow"></div></a>').appendTo('#destinationList');
        });
    }
});

更多关于empty()的信息

【讨论】:

  • 他写他刷新页面,所以由于web应用程序是无状态的,所以不需要它。如果我理解他的话。
  • 谢谢。解决了问题:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-28
  • 1970-01-01
  • 2013-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多