Ajax - 不会更改URL

时间:2015-06-01 18:09:00

标签: javascript php jquery ajax zend-framework2

我使用Ajax更改了页面内容,但问题是网站网址保持不变,因此它根本不加载页面,只加载页面上的文本。因此,例如,我单击“登录”链接并更改内容,但URL保留在站点/,而不是站点/登录。实际登录表单不会加载,因为它甚至不会调用它,只加载基本文本。我该如何解决这个问题? 附:使用Zend为网站 脚本:

$(document).ready(function() {
    $('a').click(function() {
        var toLoad = $(this).attr('href');
        $('#content').load(toLoad);
        return false;
    });
});

1 个答案:

答案 0 :(得分:1)

Ajax不会重新加载页面或加载其他页面,因此当您发出ajax请求时,url不会更改。

如果您希望更改网址,例如以便可以共享和标记您的填充ajax的网页,则需要手动更改网址。

您可以使用html5历史记录API。

一个简单的例子:

// we need the click event here
$('a').click(function(e) {
    // cancel default click action using `e`
    e.preventDefault();

    var toLoad = $(this).attr('href');
    $('#content').load(toLoad);

    // check if the html5 history api is available in the browser first
    if (window.history && window.history.pushState) {
      // push the state to the url in the address bar
      history.pushState({}, e.target.textContent, e.target.href);
    }

});

现在地址栏中的网址应该更改为链接的网址,但链接并未真正跟踪,而是发出了ajax请求。

请注意,您还需要确保所有网址都正确加载。这只是一个简单的例子,看起来你的链接网址不会加载一个完整的页面。

例如,查看documentation on mozilla.org以获取更多信息。