1. 程式人生 > >PHP中關於href傳值和取值的問題

PHP中關於href傳值和取值的問題

問題:在網頁開發過程中或多或少都會遇見如:index.php?id=1&page=2這類的東西,那麼我們如何在index.php中把傳過來的值獲取到呢?


下面是在javascript中獲取href傳過來的值:

方法一:用正則表示式

function getQueryString(name) {  
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");  
        var r = window.location.search.substr(1).match(reg);  
        if (r != null) return unescape(r[2]);  
        return null;  
    }
getQueryString("name")//name為去要取的引數,用字串。

方法二:

function getParam(paramName) {
        paramValue = "", isFound = !1;
        if (this.location.search.indexOf("?") == 0 && this.location.search.indexOf("=") > 1) {
            arrSource = unescape(this.location.search).substring(1, this.location.search.length).split("&"), i = 0;
            while (i < arrSource.length && !isFound) arrSource[i].indexOf("=") > 0 && arrSource[i].split("=")[0].toLowerCase() == paramName.toLowerCase() && (paramValue = arrSource[i].split("=")[1], isFound = !0), i++
        }
        return paramValue == "" && (paramValue = null), paramValue
    }
    var data = getParam("vote_id");
    alert(data);

 

第三種帶有中文的href

function getUrlParam(name){
        //正則表示式過濾
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        //正則規則
        console.log("reg==="+reg);
        //search:返回URL的查詢部分
        console.log("location.search==="+location.search);
        //substr(1):從字串第一個位置中提取一些字元
        console.log("location.search.substr(1)==="+location.search.substr(1));
        //match():在字串內檢索與正則表示式匹配的指定值,返回一個數組給r
        console.log("window.location.search.substr(1).match(reg)==="+window.location.search.substr(1).match(reg));
        var r = window.location.search.substr(1).match(reg);
        //獲取r陣列中下標為2的值;(下標從0開始),用decodeURI()進行解碼
        console.log("decodeURI(r[2])==="+decodeURI(r[2]));
        console.log("-----------------分隔符------------------------");
        if (r != null) return decodeURI(r[2]); return null;
    }

其他引數獲取介紹: 
//設定或獲取物件指定的檔名或路徑。
alert(window.location.pathname);


//設定或獲取整個 URL 為字串。
alert(window.location.href);

//設定或獲取與 URL 關聯的埠號碼。
alert(window.location.port);

//設定或獲取 URL 的協議部分。
alert(window.location.protocol);

//設定或獲取 href 屬性中在井號“#”後面的分段。
alert(window.location.hash);

//設定或獲取 location 或 URL 的 hostname 和 port 號碼。
alert(window.location.host);

//設定或獲取 href 屬性中跟在問號後面的部分。
alert(window.location.search);


下面是在PHP中獲取href傳過來的值

$vote_id = isset($_GET["vote_id"])?$_GET["vote_id"]:"";
//直接用$_GET方法就可以獲得index.php?vote=2,中vote的值
echo $vote_id;//在頁面上顯示出其值為2;