網站開發中web頁面跳轉幾種方式詳解

在作web開發中,頁面跳轉的方式有不少種,然而有些時候這些跳轉如何用到恰到好處卻很容易被忽視。javascript

客戶端觸發跳轉有以下幾種

  1. 使用meta元信息
    php

<!--以下表示5秒後跳轉到url指定的連接,推薦使用這種方式-->
<meta http-equiv="refresh" content="5;url=http://my.oschina.net/ososchina/blog">

  2.使用javascript中的window.location對象html

<!--這裏的代碼忽略了搜索引擎對於連接價值的轉移,它會被當作'暫時地'重定向。-->
<script type="text/javascript">
//修改window.location.href
window.location.href ='http://my.oschina.net/ososchina/blog';

//替換url,注意這種方式有時並非有效的,須要強制reload才行
//window.location.replace('http://my.oschina.net/ososchina/blog');
//window.location.reload(true);

//修改window導航
//window.navigate ('http://my.oschina.net/ososchina/blog') 
</script>;

補充一點:在html5中,利用新的api實現前端頁面mvc的跳轉也是一種不錯的方式(注意:服務端不跳轉),利用這種方式能夠實現前端MVC開發前端

<script type="text/javascript">
var state = { 
action : "page",
 title : "HTML 5 History API simple demo",
url : "yourpage"
};
history.pushState(state, "HTML 5 History API simple demo", state.url);
window.onpopstate = function (e) {
switch (e.state.action) {
 case "home" :
    document.title = "HOME ……";
    $.get("index.php").done(function (data) { $("#wrapper").html(data); });
     break;
   case "page" :
     document.title = e.state.title;
     $.get(e.state.url).done(function (data) { $("#wrapper").html(data); });
   break;
 }
}
</script>;

以上是客戶端觸發的跳轉html5

-------------------------------------------------------------------------------------------java

服務端觸發的跳轉的方式

  1. php中使用header跳轉web

header('Location:http://my.oschina.net/ososchina/blog'); 
//這裏的代碼忽略了搜索引擎對於連接價值的轉移,它會被當作'暫時地'重定向。

推薦使用下面的方式
後端

header('HTTP/1.1 301 Moved Permanently');//固定重定向
header('Location: http://my.oschina.net/ososchina/blog');

有時,設置http 響應頭是很是重要的,這些能夠幫助搜索引擎和瀏覽器「理解」請求的狀態api

下面提供一種發送http響應頭的php函數瀏覽器

/**
 * 發送HTTP狀態
 * @param integer $code 狀態碼
 * @return void
 */
function send_http_status($code) {
    static $_status = array(
            // Informational 1xx
            100 => 'Continue',
            101 => 'Switching Protocols',
            // Success 2xx
            200 => 'OK',
            201 => 'Created',
            202 => 'Accepted',
            203 => 'Non-Authoritative Information',
            204 => 'No Content',
            205 => 'Reset Content',
            206 => 'Partial Content',
            // Redirection 3xx
            300 => 'Multiple Choices',
            301 => 'Moved Permanently',
            302 => 'Moved Temporarily ',  // 1.1
            303 => 'See Other',
            304 => 'Not Modified',
            305 => 'Use Proxy',
            // 306 is deprecated but reserved
            307 => 'Temporary Redirect',
            // Client Error 4xx
            400 => 'Bad Request',
            401 => 'Unauthorized',
            402 => 'Payment Required',
            403 => 'Forbidden',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            406 => 'Not Acceptable',
            407 => 'Proxy Authentication Required',
            408 => 'Request Timeout',
            409 => 'Conflict',
            410 => 'Gone',
            411 => 'Length Required',
            412 => 'Precondition Failed',
            413 => 'Request Entity Too Large',
            414 => 'Request-URI Too Long',
            415 => 'Unsupported Media Type',
            416 => 'Requested Range Not Satisfiable',
            417 => 'Expectation Failed',
            // Server Error 5xx
            500 => 'Internal Server Error',
            501 => 'Not Implemented',
            502 => 'Bad Gateway',
            503 => 'Service Unavailable',
            504 => 'Gateway Timeout',
            505 => 'HTTP Version Not Supported',
            509 => 'Bandwidth Limit Exceeded'
    );
    if(isset($_status[$code])) {
        header('HTTP/1.1 '.$code.' '.$_status[$code]);
        // 確保FastCGI模式下正常
        header('Status:'.$code.' '.$_status[$code]);
    }
}

而後咱們來優化一下

send_http_status('301');//固定重定向
header('Location: http://google.com/');

問題來了:這裏挖掘機技術必須強,使用http響應後須要注意的是,在響應頭髮送以前必須沒有輸出流輸出內容,所以,這種讓人滿意的方法有時並不適用;下面進行改造:

<?php
// 若是以前沒有任何輸出, 就送出 Location 的導向資訊
if (!headers_sent()) {
    send_http_status('301');//固定重定向
    header('Location: http://my.oschina.net/ososchina/blog');
    exit;
}else{
 /**
  *echo "<script type='text/javascript'>";
  *echo "window.location.href ='http://my.oschina.net/ososchina/blog'";
  *echo '</script>';
  */ 
  //或下面的這種方式(推薦)
  echo "<meta http-equiv='Refresh' content='0;URL=http://my.oschina.net/ososchina/blog'>";
}
?>

固然有時候會出現n秒後跳轉過渡頁面,這個也不是很困難,但這種重定向只需默認的「臨時重定向」就行,避免SEO權值轉移。

<?php
   /**
 * URL重定向
 * @param string $url 重定向的URL地址
 * @param integer $time 重定向的等待時間(秒)
 * @param string $msg 重定向前的提示信息
 * @return void
 */
function send_redirect($url, $time=0, $msg='') {
    //多行URL地址支持
    $url        = str_replace(array("\n", "\r"), '', $url);
    if (empty($msg))
        $msg    = "系統將在{$time}秒以後自動跳轉到{$url}!";
    if (!headers_sent()) {
        // redirect
        if (0 === $time) {
            header('Location: ' . $url);
        } else {
            header("refresh:{$time};url={$url}");
            echo($msg);
        }
        exit();
    } else {
        $str    = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
        if ($time != 0)
            $str .= $msg;
        exit($str);
    }
}
?>

--------------------------------------------------------------------------------

在頁面有2個紅色的詞語「觸發」,這裏的意思是經過觸發事件來進行跳轉的,在http請求中(http基於tcp鏈接),通常是 「請求-應答」模式,但這種模式是獨立於頁面跳轉的。

實際上頁面跳轉分爲2中方式 :客戶端跳轉,客戶端和服務端一塊兒跳轉

客戶端跳轉在目前mvc主流框架中使用較爲普遍,這種跳轉通常經過服務端控制(Controller)觸發,如j2ee servlet中的Dispatcher和forward以及php中的include,display,客戶端和服務端一塊兒跳轉通常具備強制性,這個不管前端和後端都可使用,但後端使用的一個好處是能夠發送狀態碼,對於SEO等工做具備不少好處。

相關文章
相關標籤/搜索