更改Ajax调用中的URL的问题

时间:2015-12-17 11:46:37

标签: javascript jquery ajax url

我有一个关于分页概念的休息服务电话。现在在点击下一个按钮/图标的分页概念中,我可以调用其余服务并返回所需的值,但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

3 个答案:

答案 0 :(得分:2)

您好我的建议是尝试将nextPage变量声明为全局变量,因为每当您点击该函数时,新值将被分配给该nextPage变量。所以也尝试

     var nextPage=0;

function nextPage(currentPage, totalPageCount) {
      /......../

      nextPage= currentPage+1;

     /......../

}

答案 1 :(得分: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

答案 2 :(得分:1)

以下代码将保留页面不刷新,只更改网址。

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

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