2010-04-27 30 views
1

我有一個網站,有許多網頁:AJAX使用jQuery deeplinking地址

例如:

HOME:http://mywebsite.com/index.html

某些分頁: http://mywebsite.com/categorie/somepage.html

我決定使我的網頁與AJAX動態加載而無需重新加載頁面。所以我決定用的jQuery爲了讓deeplinking和後退,前進導航地址插件(http://www.asual.com/jquery/address/docs/):

<script type="text/javascript" src="uploads/scripts/jquery.address-1.2rc.min.js"></script> 
<script type="text/javascript"> 
       $('a').address(function() { 
        return $(this).attr('href').replace(/^#/, ''); 
       }); 
</script> 

現在,安裝插件後,如果我去上http://mywebsite.com/index.html(HOME)並點擊在一些頁面鏈接,jquery成功加載http://mywebsite.com/categorie/somepage.html而無需重新加載頁面和我的瀏覽器上顯示的地址欄: http://mywebsite.com/index.html/#/categorie/somepage.html這太棒了!

然而,問題是:如果我在這個動態生成的URL複製:http://mywebsite.com/index.html/#/categorie/somepage.html 到Web瀏覽器的地址欄,它會考慮到我的網站的index.html頁面,而不是針對「部分專頁」頁面。此外,前進/後退按鈕無法正常工作,它們只替換URL欄中的地址,但內容保持不變。

我想我需要編寫一些將動態URL與正確頁面關聯的JavaScript規則?

一些幫助,將不勝感激。謝謝:)

+0

值得考慮:如果沒有JavaScript的用戶訪問這樣的鏈接? – RoToRa 2010-04-27 10:24:44

+0

我正在考慮同樣的事情......也許.htaccess重定向規則? – b0nd 2010-04-27 14:41:12

回答

1

事情是這樣的:

$(function() { 
    var path = location.hash.substring(1); // remove '#' 
    if (path) { 
     $.address.value(path); 
    } 
}); 

更新:

如果手動加載頁面(例如,在鏈接點擊)而不是使用地址事件處理程序(如$.address.change(function() { ... })) ,然後在path用Ajax調用的頁面替換上面的$.address.value(path);

$(function() { 
    var path = location.hash.substring(1); // remove '#' 
    if (path) { 
     // get page at path 
    } 
}); 
+0

似乎沒有工作... :(感謝您的幫助無論如何 – b0nd 2010-04-27 14:43:41

+0

我已經更新了答案 – 2010-04-27 15:38:08

+0

我很抱歉,但我不太明白 但是,我發現另一個插件,似乎提供同樣的事情: http://benalman.com/projects/jquery-bbq-plugin/這一個使用通過hashchange事件工作,我會試一試。 – b0nd 2010-04-27 16:27:26

2

複製粘貼網址到地址欄正在工作 返回/下一個按鈕也在工作。

應該在那裏使它工作

人知道如何使#!所以它的索引由谷歌?

#/是一回事嗎?

基本上這個工作對我來說WordPress的:

// ajax setup 
$.ajaxSetup({cache:false, success: function() { 
// optional action here 
}}); 

// Event handlers 
$.address.init(function(event) { 
    $('#nav li a').address(function() { 
    return $(this).attr('href').replace(location.pathname, ''); 
    }); 
}).bind('externalChange', {}, function(event) { 
    var post_id; // get page id 
    var nav_id; // get nav class 
    // for back button 
    switch (true) { 
    case (event.value == undefined): 
      post_id = 2; nav_id = 'home'; break; 
    case (event.value == "/about"): 
      post_id = 19; nav_id = 'about'; break; 
    case (event.value == "/product"): 
      post_id = 26; nav_id = 'product'; break; 

    ...etc.... 

    default: post_id = 2; nav_id = 'home'; 
    } 

    // content loader on back/next button 
    $("#content-wrap").load("http://www.somesite.com/home/",{id:post_id}); // load content 
}); 

// content loader by #nav 
$(document).on("click","#nav li a",function(e){           
    var post_id = $(this).attr("id"); // get page id 
    $("#content-wrap").load("http://www.somesite.com/home/",{id:post_id}); // load content 
    return false; // keep url, no refresh 
});