1. 程式人生 > >登入成功後跳回到原來頁面

登入成功後跳回到原來頁面

應用場景:一般網頁遊客和登入使用者看到的內容是有區別的,如果一個未登入的使用者在看到登入提示後跳轉到登入介面登入,那麼登入成功後怎麼返回到該頁面呢?

假設使用者在 www.example.com/a.html 看到登入提示,然後點選登入跳轉到 www.example.com/login.html,登入介面使用ajax驗證使用者登入資訊,當返回資訊為成功時,在回撥函式裡要做這些邏輯的處理:

1.判斷document.referrer是否為空,若為空本頁面就不是從其它頁面跳轉過來的,就將頁面跳轉至網站首頁

2.若document.referrer不為空,則需要判斷前一個頁面是否是本站點的頁面,以免跳到其它站點去了,如果是其它站點則跳轉至首頁;

3.若document.referrer不為空且為本站點頁面,則需要跳轉至該頁面

location.href = URL的方式最終以URL值呼叫assign()方法!

location.assign() 方法載入新的文件。

window.location 物件用於獲得當前頁面的地址 (URL),並把瀏覽器重定向到新的頁面。

因此在登入成功的回撥函式裡執行下列操作就可以實現登入跳回重新整理頁面了

var prevLink = document.referrer;  
if($.trim(prevLink)==''){  
    location.href = 'www.example.com/index.html';  
}else{  
    if(prevLink.indexOf('www.example.com')==-1){    //來自其它站點  
        location.href = 'www.example.com/index.html';  
    }  
    if(prevLink.indexOf('register.html')!=-1){      //來自注冊頁面  
        location.href = 'www.example.com/index.html';  
    }  
    location.href = prevLink;  
}