Using Javascript / jQuery to get a query string in a segment based URL

I use the PHP Codeigniter framework, which uses URLs such as http://www.mydomain.com/age/11/name/john/color/red, instead of regular lijke requests http://www.mydomain.com/index.php?age=11&name=john&color=red.

How to get key value agefrom url using javascript / jQuery?

After capturing the value, 11I will pass it to the jQuery object when the event fires.

$( "#searchdistance_slider" ).slider({
        range: "min",
        value: 5,
        min: 0.5,
        max: 10,
        slide: function( event, ui ) {
            $( "#search_distance" ).val(ui.value + " miles");
            window.location.replace("http://www.domain.com/" + age); 
            /* passing the value of age into URL to redirect to */
        }
    });

UPDATE

  • The key / value pair can change position , and the number of key / value pairs in the URL is not defined.
  • Javascript, , age, 20 http://www.mydomain.com/age/20/name/john/color/red
+5
4

jQuery URL parser.

.segment(n) URL "age" , , .

.fsegment(n), age .

.segment() - :

var parts = $.url(your_url).segment();
var params = [];
for (var i=0; i<parts.length/2; i++) {
   params[parts[2*i]] = parts[2*i+1];
}
var age = parseInt(params['age']);

( , .)

age, . , .

, - :

var parts = $.url(your_url).segment();
var newpath = '';
for (var i=0; i<parts.length/2; i++) {
  if (parts[2*i] == 'age') {
    newpath += '/age/' + (parseInt(parts[2*i+1]) + 42); // put your age modifiy
                                                        // code here
  } else {
    newpath += '/' + parts[2*i] + '/' + parts[2*i+1];
  }
}
alert(newpath);
+3

- :

var parts = {},
    bits = location.pathname.substr(1).split('/'); // get rid of first / and split on slashes

for (var i = 0; i<bits.length; i += 2) {
    parts[bits[i]] = bits[i+1];
}

age parts.age.

+1

, php script:

<?php
$getAgre = ( isset($_GET['age']) && strlen($_GET['age'])>0 )? $_GET['age'] : 'null';
echo '<script>var age = '. $getAge .';</script>';
?>

edit: , $_GET ['age'], JS , .slider() , get

0

You can use a variable window.location.hrefthat will give you the entire current url and then play a bit with the string to get the information you need. Substring, separation, even regular expression.

This will work:

var ageMatch= window.location.href.match(/age\/([\d]*)/);
var age= ageMatch[1];

For the record only, you can also easily update the url:

var newUrl= window.location.href.replace(/age\/([\d]*)/, age);
window.location.href= newUrl;
0
source

All Articles