简体   繁体   English

如何使用Ajax和历史记录动态加载页面?

[英]How to load a page dynamically using Ajax & History?

I am confused with the following problems in using Ajax and History: 在使用Ajax和历史记录时,我对以下问题感到困惑:

Specifications: 规格:

  • I have a page that calls another page using Ajax. 我有一个页面使用Ajax调用另一个页面。
  • Now the loaded page has datatables which inturn uses Ajax to get data(As of now 2 ajax calls) 现在,已加载的页面具有数据表,这些数据表又使用Ajax来获取数据(截至目前有2个ajax调用)
  • I have used history.js for page navigation, which uses common ajax call for loading the content in page div 我已经使用history.js进行页面导航,它使用常见的ajax调用将内容加载到页面div中

Now, I face with the following problem: 现在,我面临以下问题:

  • For first datatable page call, I get one ajaxcall. 对于第一个数据表页面调用,我得到了一个ajaxcall。
  • Surprisingly, when I navigate to another page using history and call the datatable page, the ajax call now doubles. 令人惊讶的是,当我使用历史记录导航到另一个页面并调用数据表页面时,ajax调用现在会加倍。 It goes on in a linear manner. 它以线性方式进行。

This is a new problem I have been facing while loading a page using ajax which inturns contain Ajax call. 这是我在使用ajax加载页面时遇到的一个新问题,而该页面反过来又包含Ajax调用。 What can be the major cause of this problem? 造成此问题的主要原因是什么? Also, what is the solution of this problem? 另外,该问题的解决方案是什么?

My common code looks like this: 我的通用代码如下所示:

<script>
var index=function(url,update_id,state){
        $.ajax({
          url: url,
        }).done(function(data) {
            $("#"+update_id).html('');
            $("#"+update_id).html(data);
            if(state == 1){
                history.pushState({url: url,id:update_id},"name",url);
            }
        });
    }
jQuery(document).ready(function($) {
    $(document.body).on('click','.link_click',function(){
        var url = $(this).attr('href');
        var update_id = $(this).attr('update_id');
        index(url,update_id,1);
    })
});

window.addEventListener('popstate', function(event) {
    if(event.state.url != null){
        index(event.state.url,event.state.id);
    }
});
</script>

My link looks like this: 我的链接看起来像这样:

<a href="/page1/index" onclick = "return false;" update_id="new" class="link_click">My Contact</a>

I am using this common code for linking every page using Ajax and history 我正在使用此通用代码通过Ajax和历史链接每个页面

Are you using a framework for your project? 您是否正在为项目使用框架? I've noticed similar behaviour before using the Yii Framework. 在使用Yii框架之前,我已经注意到类似的行为。 What I noticed is that if you create your objects with a static Id, it will cause a multiplication in the number of ajax calls. 我注意到的是,如果使用静态ID创建对象,则会导致Ajax调用数量成倍增加。

Try giving your objects unique ids so that the events don't get clogged. 尝试为您的对象提供唯一的ID,以免事件被阻塞。

只是一个想法:加载Ajax的页面是否有可能再次将点击事件附加到“ link_click”链接上?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM