Adding a parameter to the URL with JavaScript

后端 未结 30 2240
刺人心
刺人心 2020-11-22 07:33

In a web application that makes use of AJAX calls, I need to submit a request but add a parameter to the end of the URL, for example:

Original URL:

30条回答
  •  终归单人心
    2020-11-22 08:07

    This was my own attempt, but I'll use the answer by annakata as it seems much cleaner:

    function AddUrlParameter(sourceUrl, parameterName, parameterValue, replaceDuplicates)
    {
        if ((sourceUrl == null) || (sourceUrl.length == 0)) sourceUrl = document.location.href;
        var urlParts = sourceUrl.split("?");
        var newQueryString = "";
        if (urlParts.length > 1)
        {
            var parameters = urlParts[1].split("&");
            for (var i=0; (i < parameters.length); i++)
            {
                var parameterParts = parameters[i].split("=");
                if (!(replaceDuplicates && parameterParts[0] == parameterName))
                {
                    if (newQueryString == "")
                        newQueryString = "?";
                    else
                        newQueryString += "&";
                    newQueryString += parameterParts[0] + "=" + parameterParts[1];
                }
            }
        }
        if (newQueryString == "")
            newQueryString = "?";
        else
            newQueryString += "&";
        newQueryString += parameterName + "=" + parameterValue;
    
        return urlParts[0] + newQueryString;
    }
    

    Also, I found this jQuery plugin from another post on stackoverflow, and if you need more flexibility you could use that: http://plugins.jquery.com/project/query-object

    I would think the code would be (haven't tested):

    return $.query.parse(sourceUrl).set(parameterName, parameterValue).toString();
    

提交回复
热议问题