PHP Style Cookie and Get Parameters in JavaScript

For lazy phpers, with this function you can read cookies and get parameters in javascript in php style.
(I use php tags to highlight the code)
Example

<?php
populateRequest
();
if( 
$_COOKIE['sid'] ) {
// do something
}
if( 
$_GET['cmd'] == 'login' ) {
// do something
}
?>

<?php
function populateRequest(){
    
String.prototype.trim = function(){
        return 
this.replace(/^s+|s+$/, '');
    }
    
cookies = document.cookie.split(';');
    
window.$_COOKIE = new Object();
    for(var 
i = 0; i < cookies.length; i++){
        
curentCookie = cookies[i];
        var 
ckv = curentCookie.split('=');
        var 
k = ckv[0];
        var 
v = ckv[1];
        if( 
k && v ){
            
k = k.trim();
            
$_COOKIE[k] = v;
        }
    }
    var 
query = location.search.replace('?', '');
    
params = query.split('&');
    
window.$_GET = new Object();
    for(var 
i = 0; i < params.length; i++){
        
curentParam = params[i];
        var 
ckv = curentParam.split('=');
        var 
k = ckv[0];
        var 
v = ckv[1];
        if( 
k && v ){
            
k = k.trim();
            
$_GET[k] = v;
        }
    }
}
?>

add new comment | read more

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.