หน้าเว็บ

วันอาทิตย์ที่ 23 ธันวาคม พ.ศ. 2555

get Query String parameter javascript

var Urls = {

    getParameterByName : function(name){
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.search);
        //var results = regex.exec(window.location.hash);
        if(results == null)
            return "";
        else
            return decodeURIComponent(results[1].replace(/\+/g, " "));
    },
    
    getObjectQueryString : function(){
        var urlParams = {};
        var match,
        pl     = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) {
            return decodeURIComponent(s.replace(pl, " "));
        },
        query  = window.location.search.substring(1);

        while (match = search.exec(query)){
            urlParams[decode(match[1])] = decode(match[2]);
        }
        
        return urlParams;
    }
}
/**
* example to use
* url : ?i=main&mode=front&sid=de8d49b78a85a322c4155015fdce22c4&enc=+Hello%20&empty
*
* var object = Urls.getObjectQueryString();
* console.log(object);
* //object {i : "main", mode : "front", sid : "de8d49b78a85a322c4155015fdce22c4", enc : " Hello ", empty : ""}
* console.log(object.mode);
* //front
*
* var sid = Urls.getParameterByName("sid");
* console.log(sid);
* //de8d49b78a85a322c4155015fdce22c4
*/

Thank you  : http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values

ไม่มีความคิดเห็น:

แสดงความคิดเห็น