在Ajax调用中更改URL的问题

Issue with changing the URL in the Ajax call

本文关键字:URL 问题 Ajax 调用      更新时间:2023-09-26

我有一个针对分页概念的rest服务调用。现在,在分页概念中,单击下一个按钮/图标,我可以调用rest服务,它会返回所需的值,但URL没有更改,我需要更改URL中的页码。我的代码是下一个图标事件如下,"

function nextPage(currentPage, totalPageCount) {
            alert(currentPage+ " Begin nextPage Method " + totalPageCount);
            var nextPage = currentPage+1;
            var ctx = "${context}";
            var url = ctx+"/adtrack/storelist/National/1/"+nextPage;
            console.log(url);
            if(nextPage  <= totalPageCount)
                {
                jQuery.ajax({
                   url: url,
                   type: "GET",
                   success: function(msg) {
                    alert("Success");
                   },
                   error : function(msg) {
                     alert("Fail");
                   }
                  });
                }
            else{
                alert("Unable to perform the action!!!");
            }
            // return true or false, depending on whether you want to allow the `href` property to follow through or not
        }

在上面的调用中,它会点击URL并返回值,但我也需要将当前URL更改为最新URL。如何更新URL?

我点击的URL必须更新为浏览器当前URL

嗨,我的建议是尝试将nextPage变量声明为全局变量,因为每当您点击该函数时,就会将新值分配给该nextPage变量

     var nextPage=0;
function nextPage(currentPage, totalPageCount) {
      /......../
      nextPage= currentPage+1;
     /......../

}

您可能应该使用History API,它允许主要处理浏览器历史记录。

function nextPage(currentPage, totalPageCount) {
            alert(currentPage+ " Begin nextPage Method " + totalPageCount);
            var nextPage = currentPage+1;
            var ctx = "${context}";
            var url = ctx+"/adtrack/storelist/National/1/"+nextPage;
            console.log(url);
            if(nextPage  <= totalPageCount)
                {
                jQuery.ajax({
                   url: url,
                   type: "GET",
                   success: function(msg) {
                    alert("Success");
                    /* History API goes below, replace /testurl with the string you want */
                    window.history.pushState(null, null, '/testurl');
                   },
                   error : function(msg) {
                     alert("Fail");
                   }
                  });
                }
            else{
                alert("Unable to perform the action!!!");
            }
            // return true or false, depending on whether you want to allow the `href` property to follow through or not
        }

请记住,一些较旧的浏览器可能不支持

http://caniuse.com/#feat=history

更多关于历史API的信息点击这里

https://css-tricks.com/using-the-html5-history-api/

https://developer.mozilla.org/en-US/docs/Web/API/History_API

下面的代码将保护页面不被刷新,只更改url。

 history.pushState({id: '<SOME-ID>'}, '', 'newUrl');

有关更多信息,请参阅https://rosspenman.com/pushstate-jquery/