如何获取查询字符串值

时间:2014-05-05 17:54:36

标签: javascript

我只需从以下网址中获取值60408571:

http://www.domain.com/ProductDetail.aspx?ProductId=60408571&this-is-a-page-title-that-goes-here

到目前为止,我已经成功地在?ProductId=之后抓住了所有内容,但这会返回:

60408571&this-is-a-page-title-that-goes-here

我目前使用的JavaScript是:

if(window.location.href.indexOf("ProductId") > -1) {
    s.prop14 = window.location.search.replace("?ProductId=", "");
}

如果用户所在的网页是网址中包含ProductId的网页,我只想获取数值。

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

谢谢汤姆。我根据Tom提供的参考修改了我的代码,现在我已经:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

if(window.location.href.indexOf("ProductId") > -1) {
    //s.prop14 = window.location.search.replace("?ProductId=", "");
    s.prop14 = getParameterByName('ProductId');
}

效果很好!再次感谢。

答案 1 :(得分:0)

如果网址不会改变,您也可以这样做:

var productId = findProductId(window.location.query);

function findProductId(url){
    return url.split('&')[0].split('=')[1];
}
相关问题