使用javascript从重写的URL中获取参数

AdR*_*ock 0 javascript regex url mod-rewrite

我正在尝试使用javascript获取url参数,因此我可以将参数传递给谷歌地图

问题是我在网址上使用mod重写

www.mysite.com/1/my-event

代替

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

我已经尝试过做一个警报,但它出现了空白

这是javascript函数,如果我不重写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];
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*ski 7

您的JavaScript无法使用带有查询字符串的重写格式.

您必须从location.pathname(/1/my-event在您的示例中)中获取值,而不是:

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

var id = params[0];
var name = params[1];
Run Code Online (Sandbox Code Playgroud)