简体   繁体   English

匹配当前页面卸载时单击URL的字符串

[英]Match string with clicked URL on unload of current page

I have a form with URL: 我有一个带有URL的表格:

localhost:83/mysite/item/UpdateItems/225

I have a temporary table in which I have loaded data and display in my form from temporary table. 我有一个临时表,已在其中装载数据并从临时表以表格形式显示。

When I refresh the page I don't want to fire an ajax call and truncate the table. 当我刷新页面时,我不想触发ajax调用并截断表。 But if I click on another link from menu then I do want to fire the ajax call and truncate tables. 但是,如果我单击菜单中的另一个链接,那么我确实想触发ajax调用并截断表。

Is it possible? 可能吗?

I have used beforeunload for truncate table when click on another menu: 单击另一个菜单时,我已使用beforeunload截断表:

 $(window).on('beforeunload', function(){
     //My ajax code for truncate table
});

But this works on page refresh also, which I don't want. 但这也可以在页面刷新上使用,我不需要。 So I tried with matching string in URL: 所以我尝试在URL中匹配字符串:

$(window).on('beforeunload', function(e){
    if (document.URL.indexOf("UpdateItems") > -1) {

        console.log("page refresh");

     }else{
         console.log("not refreshed");  
      }
});

But this always go in first page refresh condition even if I have clicked on another menu. 但是,即使我单击了另一个菜单,也始终处于首页刷新状态。

Try this , it will definitely work, 试试这个,肯定会起作用,

    <SCRIPT language="javascript">

    window.onbeforeunload=before;

    function before(evt)
    {
       if(window.location.toString().indexOf("UpdateItems") > -1) { 

        console.log("page refresh");

       }
       else{
         console.log('Not');
       }
    }
    </script>

If (and this is a pretty big if) the refresh is done by clicking a link on the page (and not say from a script or by the user clicking the browsers refresh button) this approach might work: 如果刷新是通过单击页面上的链接(而不是从脚本说或用户单击浏览器的刷新按钮)完成的(如果这是一个很大的数目),则此方法可能有效:

Set a flag to false whenever someone click a link that should not lead to the table being truncated, and only run the code if the flag is true: 每当有人单击不应导致表被截断的链接时,请将标志设置为false,并且仅在标志为true时才运行代码:

// As default the flag is true.
flagTruncate = true;

// When someone clicks a link with UpdateItems in the URL, the flag is  set to false.
$("a[href*='UpdateItems']").click(function () {
    flagTruncate = false;
});

//Only truncate the table when the user is leaving if the flag is still true.
$(window).on('beforeunload', function() {
    if(flagTruncate) {
        //Truncate the table.
    }
});

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

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