在 jQuery AJAX 拉取后更新 URL



我有一个名为index.html的网页,它通过jQuery load()方法连接到其他页面(portfolio.php,friendzone.php等等)。

示例:我的菜单具有以下代码:

<a href="./" class="button"><div id="homepageBtn"></div></a>
<a onclick="showPage('progressi')" class="button"><div id="progressiBtn"></div></a>
<a onclick="showPage('interessi')" class="button"><div id="interessiBtn"></div></a>
<a onclick="showPage('friendzone')" class="button"><div id="friendzoneBtn"></div></a>
<a onclick="showPage('contact')" class="button"><div id="emailBtn"></div></a>

当我单击不是主页选项的内容时,将调用 showPage() 函数:

function showPage(page) {
    $("#post-title").fadeOut (200, function() {
        $("#post-title").html(page); // Edit the page title in the div
        Cufon.refresh(); // I use Cufon plugin, so I reload it
    }).fadeIn(500);
    $("#post-content").fadeOut (200, function() {
        $("#post-content").load(page + ".php", function() { // If I pass for example "contact", it loads me the page contact.php in the "post-content" div
            $('a.boxed').colorbox({rel: 'Galleria'}); // I use colorbox jQuery plugin, so I reload it here
            $('a.iframe').colorbox({iframe: true, width: "80%", height: "80%"}); // Same here
        });
    }).fadeIn(500);
}

一切都完美无缺,除了一件事:

当我在我的div 中加载另一个页面内容时,URL 不会更改。我相信这对 Google 抓取工具和想要通过单击浏览器的后退按钮或共享指向我网站特定页面的链接进入上一页的用户来说非常糟糕。

有什么方法可以根据我在div 中加载的内容实现不同的 URL?

您可以在不更改实际页面网址的情况下修改浏览器网址,但我认为这不会影响爬虫。您将需要为机器人生成站点地图。设置一个谷歌网站管理员帐户并在那里提交您的站点地图。

使用新 URL 更新地址栏而不进行哈希处理或重新加载页面

window.history.pushState("object or string", "Title", "/new-url");

为什么不做一个共享.php用 get 变量重定向到主页?例如,在每个页面上,您都有一个链接到index.php?page=friendzone的"共享"按钮

当有人加载共享链接时,它将包含类似以下内容。将其放在您的<head>标签中。

<? 
//Include this right before your end </head>.
if(isset($_GET['page']))
{
    ?>
    <script>
    $(function() {
        showPage('<? echo htmlentities($_GET['page']); ?>');
    });
    </script>
    <?
}
?>

在节目页面中,您可以执行以下操作:

if ( history.pushState ) history.pushState( {}, page, "/?page="+page );

尝试在下面编写其工作代码。

         $.ajax
         ({
           type: "POST",
            url: 'Services/MyService.asmx/returnString2',
       dataType: "json",
           data: JSON.stringify({ fname: "yan" , lname: "key" }),
    contentType: "application/json; charset=utf-8",
          error: function (jqXHR, textStatus, errorThrown)   //what to do if fails
                 {
                   window.history.pushState("object or string", "Title", "/new-url");
                 },
        success: function (data)           //what to do if succedded
                 {
                   window.history.pushState("object or string", "Title", "/new-url");
                 }

});

最新更新