admin管理员组

文章数量:1356385

in my script there a simple list shows links for editing

<ul>
<li><a href="edit.php?id=5" class="edit">click here</a></li>
<li><a href="edit.php?id=5" class="edit">click here</a></li>
<li><a href="edit.php?id=5" class="edit">click here</a></li>
<li><a href="edit.php?id=5" class="edit">click here</a></li>
</ul>

what i need is to read the variable id so i can send it through .ajax call and i tried this function

$(document).ready(function(){
    function getUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1)
                                         .split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
     }
     $('.edit').click(function(){
         var test = getUrlVars()["id"];
         alert(test);
     });
});

When I clicked on the link, the alert message shows undefined.

I tried another function:

$(document).ready(function(){
    var urlParams = {};
    (function () {
        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]);
     })();
     $('.edit').click(function(){
         var test = urlParams["id"];
         alert(test);
     });
 });

... but even this also shows up the alert message undefined.

in my script there a simple list shows links for editing

<ul>
<li><a href="edit.php?id=5" class="edit">click here</a></li>
<li><a href="edit.php?id=5" class="edit">click here</a></li>
<li><a href="edit.php?id=5" class="edit">click here</a></li>
<li><a href="edit.php?id=5" class="edit">click here</a></li>
</ul>

what i need is to read the variable id so i can send it through .ajax call and i tried this function

$(document).ready(function(){
    function getUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1)
                                         .split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
     }
     $('.edit').click(function(){
         var test = getUrlVars()["id"];
         alert(test);
     });
});

When I clicked on the link, the alert message shows undefined.

I tried another function:

$(document).ready(function(){
    var urlParams = {};
    (function () {
        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]);
     })();
     $('.edit').click(function(){
         var test = urlParams["id"];
         alert(test);
     });
 });

... but even this also shows up the alert message undefined.

Share Improve this question edited Oct 4, 2012 at 12:23 raina77ow 107k16 gold badges204 silver badges236 bronze badges asked Oct 4, 2012 at 12:15 Dr.NeoDr.Neo 1,2804 gold badges17 silver badges29 bronze badges 2
  • 1 vars.push(hash[0]); vars[hash[0]] = hash[1]; - what for, why do you try to process vars both like an array and like an object? – raina77ow Commented Oct 4, 2012 at 12:19
  • Precisely @raina77ow - I just reviewed a piece of code that was trying to use this function, and I noticed the same thing. Bad code bites even after 4 years I suppose ;) – kamituel Commented Feb 3, 2016 at 11:55
Add a ment  | 

6 Answers 6

Reset to default 3

The methods your tried don't take an URL as argument, but parse the current URL parameters (i.e. the URL within your brother). Just modify the first method like this to make it work:

$(function() {
    function getUrlVars(url) {
        var vars = [], hash;
        var hashes = url.slice(url.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
    $('.edit').click(function() {
        var href = $(this).attr("href");
        var test = getUrlVars(href)["id"];
        alert(test);
    });
});

Side note: you could also modify the second one, both of them do the same job.

You could try this:

JavScript

function getUrlParams() {
    var params = {};
    location.search.replace(/\?/g, '').split('&').forEach(function(item) {
      params[item.split('=')[0]] = item.split('=')[1];
    });
    return params;
}

The function will return an object like this:

{
  firstName: 'Jordan',
  lastName: 'Belfort',
  position: 'The Wolf of Wall Street',
}

Usage

var urlParams = getUrlParams();
alert('Hello ' + urlParams.firstName + ' ' + urlParams.lastName);

Note: There's actually no need to use location.href and split the url at '?', since we can get the whole query string with location.search.

As an alternative to your problem, why not put the id part of the href into a data parameter and read that? It would save you having to dissect the URL. Try this:

<ul>
    <li><a href="edit.php?id=5" data-id="5" class="edit">click here</a></li>
    <li><a href="edit.php?id=6" data-id="6" class="edit">click here</a></li>
    <li><a href="edit.php?id=7" data-id="7" class="edit">click here</a></li>
    <li><a href="edit.php?id=8" data-id="8" class="edit">click here</a></li>
</ul>
$('.edit').click(function(){
    var id = $(this).data("id");
    alert(id);
});

Try this one:

function getParameterByName( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

You almost got it right the first time, you just have to declare vars as object and get rid of vars.push(...).

Here's working example - http://jsfiddle/KN9aK/1/show/?id=yoursuperduperid

Source here http://jsfiddle/KN9aK/1/

Change it to use an object, not an array.

function getUrlVars() {
    var vars = {}, //<--object
    hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1)
                                     .split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars[hash[0]] = hash[1];  //<--add to the object
    }
    return vars;  //<--return the object
 }

Also you can use window.location.search so you do not have to do that initial slice.

本文标签: function to retrieve url variables using javascript and JqueryStack Overflow