使用JavaScript从重写的URL获取参数 [英] Get a parameter from a rewritten URL with javascript

查看:83
本文介绍了使用JavaScript从重写的URL获取参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用javascript获取url参数,以便可以将参数传递给Google地图

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

问题是我在url上使用mod重写

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

www.mysite.com/1/my-event

www.mysite.com/1/my-event

代替

www.mysite.com/mypage.php?id=1&name=我的事件

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

我已经尝试过发出警报,但它显示为空白

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

如果我不重写url,这是工作的javascript函数

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

推荐答案

JavaScript不能使用带有查询字符串的重写格式.

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

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

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

这篇关于使用JavaScript从重写的URL获取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆