如何在jquery中获取查询字符串值

时间:2016-08-06 10:01:26

标签: php jquery ajax

我想在jquery中获取查询字符串值并使用ajax将其传递给php页面。但我得到的完整字符串如task_id=2,而我只想要值2。我怎么能这样做?

$('#stop').click(function(){
var time = $('#counter').text();
var url = location.search.substr(1)
    $.ajax({
                type: "POST",
                url: "ajax-calls/updatetimestamp.php",
                data: {time,url}
                success: function() {
                    location.reload();
                },
            });
})

1 个答案:

答案 0 :(得分:0)

您不需要jQuery用于此目的。您只能使用一些纯JavaScript:

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

用法:

// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)