Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get URL parameter with Knockout JS

Tags:

knockout.js

Suppose I have a URL like this:

http://www.example.com/apples?myParam=123&myOtherParam=456

How do I use Knockout JS to retrieve the values of myParam and myOtherParam ?

like image 563
Jesse Lynn Avatar asked Jul 01 '26 15:07

Jesse Lynn


2 Answers

To parse the location. [window.location gives you the current document's location]

var paramsString = window.location.split("?")[1];
var paramValues = paramsString.split("&");
var params = new Array();
for(var param in paramValues){
    var paramValue = param.split("=");
    params[paramValue[0]] = paramValue[1];
}

to use the params:

var myParam = params.myParam; //or
var myOtherParam = params['myOtherParam'];
like image 162
NPToita Avatar answered Jul 10 '26 01:07

NPToita


You can also take a look to this post which shows a nice, simple and small fuction:

function $_GET(param) {
var vars = {};
window.location.href.replace( location.hash, '' ).replace( 
    /[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
    function( m, key, value ) { // callback
        vars[key] = value !== undefined ? value : '';
    }
);

if ( param ) {
    return vars[param] ? vars[param] : null;    
}
return vars;}

then you can get the variable in a similar way to PHP:

name = $_GET('name')

Here is the full article: read URL params with Javascript

like image 36
Alberto S. Avatar answered Jul 10 '26 01:07

Alberto S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!