简体   繁体   中英

How to get the URL parameters after redirecting using javascript?

After replacign the location with new parameters, the page after loaded doesn't get the paramaters value, despite there are values in the parameters the used code is :

function getURLParameter(name) {
    return
    decodeURI((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]);
}

$(document).ready(function () {
    $(".sub").slideUp();
    var div = getURLParameter("div");
    var ddl = getURLParameter("ddl");
    alert(div);
    //            alert("ManageTrainingNeeds.aspx?div=" + div + "&ddl=" + ddl);
    // $("#" + div).slideDown();
    //  $("#ddlObjectiveGroup").val("'" + ddl + "'");      
});
$(".btnAddSub").live("click", function () {
    var diva = $(this).parent().parent().parent().parent().parent().parent().attr("id");
    var ddl = $("#ddlObjectiveGroup option:selected").val();
    window.location.replace("ManageTrainingNeeds.aspx?div=" + diva + "&ddl=" + ddl);
});

this alert(div); return undefined .. despite the div vairable in click event has a value

Try encoding the parameters and also canceling the default action in the click event:

function getURLParameter(name) {
    return decodeURIComponent((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]);
}

$(document).ready(function () {
    var div = getURLParameter('div');
    var ddl = getURLParameter('ddl');
    alert(div + ' ' + ddl);
});

$('.btnAddSub').live('click', function () {
    var diva = encodeURIComponent($(this).parent().parent().parent().parent().parent().parent().attr('id'));
    var ddl = encodeURIComponent($('#ddlObjectiveGroup').val());
    window.location.replace('/ManageTrainingNeeds.aspx?div=' + diva + '&ddl=' + ddl);
    return false;
});

Instead of fiddling with the URLs yourself, you could use a library for the job - such as URI.js . (sorry for the self-promo)

$(document).ready(function () {
    var search = URI().search(true);
    alert(search.div + ' ' + search.ddl);
});

$('.btnAddSub').live('click', function (e) {
    var uri = URI('/ManageTrainingNeeds.aspx');
    uri.search({
        diva: $(this).parent().parent().parent().parent().parent().parent().attr('id'),
        ddl: $('#ddlObjectiveGroup').val()
    });
    window.location.href = uri.toString();
    e.preventDefault();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM