最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Get a parameter from a rewritten URL with javascript - Stack Overflow

programmeradmin2浏览0评论

I am trying to get a url parameter using javascript so i can pass the paramter to google maps

The problem is i'm using mod rewrite on the url

www.mysite/1/my-event

instead of

www.mysite/mypage.php?id=1&name=my-event

I've tried doing an alert but it es up blank

Here is the javascript function that will work if i don't rewrite the url

function gup( 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 results[1];
}

I am trying to get a url parameter using javascript so i can pass the paramter to google maps

The problem is i'm using mod rewrite on the url

www.mysite./1/my-event

instead of

www.mysite./mypage.php?id=1&name=my-event

I've tried doing an alert but it es up blank

Here is the javascript function that will work if i don't rewrite the url

function gup( 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 results[1];
}
Share Improve this question edited Nov 10, 2011 at 21:27 Pekka 450k148 gold badges987 silver badges1.1k bronze badges asked Nov 10, 2011 at 21:26 AdRockAdRock 3,10610 gold badges71 silver badges109 bronze badges 1
  • JS works on the client side. The url it has to work with is the URL you see in the address bar. The server-side rewrite with the query parameters is NOT visible to JS, unless the server-side rewrite forces a client redirect to the rewritten url. – Marc B Commented Nov 10, 2011 at 21:28
Add a ment  | 

2 Answers 2

Reset to default 10

The rewritten format, with the query-string, isn't available to your JavaScript.

You'll have to grab the value out of location.pathname (/1/my-event in your example), instead:

var params = window.location.pathname.split('/').slice(1); // ["1", "my-event"]

var id = params[0];
var name = params[1];

Just split the URL on / characters and take the last elements in the resulting array, mapping them to the names you expect.

发布评论

评论列表(0)

  1. 暂无评论