Get a parameter from a rewritten URL with javascript

假如想象 提交于 2020-01-07 05:37:05

问题


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.com/1/my-event

instead of

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

I've tried doing an alert but it comes 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];
}

回答1:


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];



回答2:


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



来源:https://stackoverflow.com/questions/8086527/get-a-parameter-from-a-rewritten-url-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!