草庐IT

javascript - 在 Chrome 和 IE 中单击后退按钮时防止重新加载 Ajax 数据

coder 2025-01-21 原文

我目前在一个主页上显示最近 10 条博客条目的网站上工作。当我向下滚动时,当我几乎到达屏幕上最后一个项目的末尾时,会自动加载另外 10 个博客条目,依此类推(这是无限滚动功能)。

如果用户单击任何博客条目,他/她将被带到另一个页面以显示有关该博客条目的详细信息。当用户单击后退按钮时,他/她将被带到显示条目的主页。

请注意,主页使用 Ajax 加载数据。

假设以下场景:

  1. 用户访问站点,并加载条目 1 到 10(通过 Ajax)。

  2. 用户向下滚动,接下来的 10 个条目,特别是条目 11 到 20 被加载(也通过 Ajax)。请注意,页面现在显示了完整的 1 到 20。

  3. 用户进一步向下滚动,现在加载了第 21 到 30 个条目,页面上总共显示了 1 到 30 个博客条目。

  4. 用户点击条目 25,显示条目 25 的页面。

  5. 用户点击后退按钮,显示所有项目,从 1 到 30。

现在,如果用户使用 FireFox、Opera 或 Safari,当该用户执行第 5 步(即单击后退按钮返回主页)时,博客条目将仅显示在屏幕上,而不会显示正在重新加载。但是,使用 IE 和 Chrome,当用户单击后退按钮时,页面将重新加载,并且仅显示项目 1 到 10。

我不喜欢 IE 和 Chrome 的行为。用户应该看到项目 1 到 30。如何确保所有浏览器的行为都像 FireFox?

谢谢。

更新

这是我使用的代码

首先,她的是我的html

<html>
    <body>

        <section id="content">
            <section id="articles">
                <!-- This section is filled by jQuery/Ajax -->
            </section>

            <section id="loading-spinner">
                <img src="ajax-loader.gif" />
            </section>

        </section>

    </body>
</html>

这是我的 jQuery

/**
 * 
 * This file uses a bunch of programming concepts, but the most important one is ensuring ajax calls run as a critical section
 * ... (this means if ajax is already called, then another instance of JavaScript cannot get into the critical section)
 * 
 * .. For more details, please read: http://stackoverflow.com/questions/22150960/critical-section-in-javascript-or-jquery
 * 
 */


load_more_posts = function () {

    // If we almost reach the bottom of the document, then load more posts
    if ( jQuery(window).scrollTop() >= jQuery(document).height() - jQuery(window).height() - 300) {

        // If the value of the promise is not pending, then we can call the load_posts function (the load_posts function will change the status to pending when it is executing the ajax request)
        if (ajax_status.state() !== "pending") {
            load_posts();

        }
    }
};


function load_posts() {

    ajax_status = jQuery.ajax({

        type:       'post',

        dataType:   'json',

        beforeSend: function(xhr) {

            if(jQuery.data(document.body, 'load_page') == false) {
                xhr.abort();
            }

            else {
                // Show the spinner
                jQuery('#loading-spinner').visible();
            }



        },

        url:        '../link/to/get_poasts.php',

        data:       {
            action:             'load_posts',

            js_query_data:      query_data,
            js_page:        jQuery.data(document.body, 'page_to_load')

        },

        success:    function (response) {

            if (response.isSuccessful) {

                var number_of_post_items = response.posts_array.length;

                for (var i = 0; i < number_of_post_items; i++) {

                    // If the item is already returned from the database and posted. then we skip it, otherwise, keep insert a new record 
                    if (jQuery('#articles').find('#article-' + response.posts_array[i].post_id).length == 0) {

                        // Add 'article'
                        jQuery('#articles').append('<article id="article-' + response.posts_array[i].post_id + '"></article>');

                        // More code here to add details about each article, such as title, excerpt...etc.


                    }
                }




                // Increase the value of the page to load by 1, and save it.
                page = jQuery.data(document.body, "page_to_load");
                page = page + 1;
                jQuery.data(document.body, "page_to_load", page);



                jQuery(window).on('scroll', load_more_posts);

            }

            else {
                // Display error message
                jQuery('#articles').append('<div>' + response.message + '</div>');

                // Make sure no further AJAX requests are made
                jQuery.data(document.body, 'load_page', false);
            }

        }
    }).always(function() {

        // Hide the spinner
        jQuery('#loading-spinner').invisible();
    });

    return ajax_status;
}



// Create a new promise. This will be used to ensure that no two calls hit the critical section at the same time
// ... (the critical section in this case is the time when we retrieve data from the database. We only want one call at a time)

var ajax_status = new jQuery.Deferred();


jQuery(document).ready(function() {

    // Hide the loading spinner first
    jQuery('#loading-spinner').invisible();


    // We resolve the promise, making sure it is ready (this is an intial state)
    ajax_status.resolve();

    // Initial values that are used
    jQuery.data(document.body, 'page_to_load', 1);

    // This parameter is used to stop loading pages when no more items are available to be displayed 
    jQuery.data(document.body, 'load_page', true);



    // Initial loading of poasts
    load_posts();



    // Enable on scrolling to load more pasts (to allow infinite scrolling)
    jQuery(window).on('scroll', load_more_posts);


});

最佳答案

你会在这个答案中找到一些关于它如何在“好的”浏览器中工作的信息:

Is there a cross-browser onload event when clicking the back button?

在这里你会找到一种在 IE 中模拟它的方法:

Differences in Internet Explorer and Firefox when dynamically loading content then going forward and back

不太确定为什么它在 Chrome 中不起作用。

关于javascript - 在 Chrome 和 IE 中单击后退按钮时防止重新加载 Ajax 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25073587/

有关javascript - 在 Chrome 和 IE 中单击后退按钮时防止重新加载 Ajax 数据的更多相关文章

  1. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  2. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  3. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  4. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  5. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  6. ruby-on-rails - 使用 config.threadsafe 时从 lib/加载模块/类的正确方法是什么!选项? - 2

    我一直致力于让我们的Rails2.3.8应用程序在JRuby下正确运行。一切正常,直到我启用config.threadsafe!以实现JRuby提供的并发性。这导致lib/中的模块和类不再自动加载。使用config.threadsafe!启用:$rubyscript/runner-eproduction'pSim::Sim200Provisioner'/Users/amchale/.rvm/gems/jruby-1.5.1@web-services/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:105:in`co

  7. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

  8. 世界前沿3D开发引擎HOOPS全面讲解——集3D数据读取、3D图形渲染、3D数据发布于一体的全新3D应用开发工具 - 2

    无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD

  9. FOHEART H1数据手套驱动Optitrack光学动捕双手运动(Unity3D) - 2

    本教程将在Unity3D中混合Optitrack与数据手套的数据流,在人体运动的基础上,添加双手手指部分的运动。双手手背的角度仍由Optitrack提供,数据手套提供双手手指的角度。 01  客户端软件分别安装MotiveBody与MotionVenus并校准人体与数据手套。MotiveBodyMotionVenus数据手套使用、校准流程参照:https://gitee.com/foheart_1/foheart-h1-data-summary.git02  数据转发打开MotiveBody软件的Streaming,开始向Unity3D广播数据;MotionVenus中设置->选项选择Unit

  10. 使用canal同步MySQL数据到ES - 2

    文章目录一、概述简介原理模块二、配置Mysql使用版本环境要求1.操作系统2.mysql要求三、配置canal-server离线下载在线下载上传解压修改配置单机配置集群配置分库分表配置1.修改全局配置2.实例配置垂直分库水平分库3.修改group-instance.xml4.启动监听四、配置canal-adapter1修改启动配置2配置映射文件3启动ES数据同步查询所有订阅同步数据同步开关启动4.验证五、配置canal-admin一、概述简介canal是Alibaba旗下的一款开源项目,Java开发。基于数据库增量日志解析,提供增量数据订阅&消费。Git地址:https://github.co

随机推荐