开发者

Getting URL in Javascript

Ok, I'm new to JavaScript and need some help here. Working on forward/backward buttons on a page. Essentially, the url looks like this http://webaddress.com/details?id=27

So, my two functions are meant to extract the url and forward to the same page decrementing or incrementing the details id as necessary when one of the buttons is clicked. For example when someone clicks on the next button, id=28 is shown; and if previous is clicked, id=26 is shown.

I think it's something like substring, I've seen it done somewhere before, but not sure how's done.

I need idea on how to approach it. Any help will be appreciated.

Update: I was using @gion_13's code below, but looks like I'开发者_C百科m missin something. It doesn't seem to work. Any other help will be appreciated.


You can use location.href to get or set the URL.

http://developer.mozilla.org/en/window.location

Use exec to extract the identifier.

extracted_id = /id=([0-9]+)$/.exec(location.href)[1]

http://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec


  1. Read the url as var url = document.location.href
  2. Use regEx or indexOf "=" or document.location.search to find current page no
  3. Parse as int and +/- page number
  4. rebuild the the url
  5. document.location.replace(newurl)


function parseUrl(){
    if(location.href.indexOf('?') == -1)
        return null;
    var aux = location.href.split('?');
     var result = {
        'href' : aux[0],
        'params' : {}
    };
    var p = aux[1].split('&');
    for(var i=0,l=p.length;i++)
        {
             var kv = p[i].split('=');
             params[kv[0]] = kv[1];
        }        
    return result;
}

function reconstructUrl(obj){
    if(!obj)
        return location;
    var url = obj.href + '?';
    for(var i in obj.params)
        url += i + '=' + obj.params[i] + '&';
    return encodeURI(url);
}

function getNextUrl(){
    var urlObj = parseUrl();
    urlObj.id++;
    return reconstructUrl(urlObj);
}

function getPrevUrl(){
    var urlObj = parseUrl();
    urlObj.id--;
    return reconstructUrl(urlObj);
}


The window.location object has the URL info you need. You can parse it using a regex. Here's some references:

  • https://developer.mozilla.org/en/window.location
  • https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp


To access the URL of the page, use document.URL, for example:

document.write(document.URL);

You can then modify the URL and open the new URL.

For lots of hints and tips, See JavaScript HTML DOM Examples.


You can do that without Javascript if you want. I think it's more efficient with PHP, because it will work even if some user has Javascript disabled.

You can try get the id like this:

<?php $my_id = $_GET['id']; ?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜