首頁 > web前端 > js教程 > jQuery添加參數到URL功能

jQuery添加參數到URL功能

Lisa Kudrow
發布: 2025-02-28 01:26:09
原創
111 人瀏覽過

此jQuery實用程序功能有效地檢查當前URL中的參數。如果不存在,它將附加參數並返回完整的,更新的URL。這對於AJAX請求更新數據庫並隨後重定向到同一頁面特別有用,但帶有指示成功更新的標誌(例如,顯示確認消息)。 jQuery add param to url function

(function($,W,D){
    var JQUERY4U = {};

    JQUERY4U.UTIL = {
        /**
         * Appends a parameter to a URL if it doesn't already exist.
         * @param {string} param - The parameter name to add.
         * @param {string} value - The parameter value.
         * @returns {string} The URL with the appended parameter.
         */
        addParamToUrl: function(param, value){
            // Check if parameter exists
            var regex = new RegExp(param + "=([^&]*)", "i");
            var existingParam = regex.exec(W.location.search);
            var existingValue = existingParam && existingParam[1] || "";

            // Construct the URL
            var loc = W.location;
            var url = loc.protocol + '//' + loc.host + loc.pathname + loc.search;

            // Add parameter if it doesn't exist
            if (existingValue === ''){
                url += (loc.search === '' ? '?' : '&') + param + '=' + value;
            }

            return url;
        }
    };

    // Example usage:
    var newUrl = JQUERY4U.UTIL.addParamToUrl('updated', 'true');
    console.log(newUrl);
    // Input: http://jquery4u.com/index.php
    // Output: http://jquery4u.com/index.php?updated=true

})(jQuery, window, document);
登入後複製

>經常詢問有關jQuery URL參數操縱的問題(常見問題解答) 使用jQuery

添加多個參數

添加多個參數,利用jQuery的

方法將數據對象序列化到URL編碼的字符串:

$.param()

>從URL
var data = { param1: "value1", param2: "value2" };
var url = "http://example.com/page?" + $.param(data); 
登入後複製
中刪除參數

> jQuery不直接支持URL參數刪除。 使用JavaScript的

對象:> URL URLSearchParams>檢查存在參數存在

let url = new URL("http://example.com/page?param1=value1&param2=value2");
url.searchParams.delete('param1');
登入後複製
使用

>有效檢查參數是否存在:>

修改參數值URLSearchParams.has()

使用
let url = new URL("http://example.com/page?param1=value1&param2=value2");
let hasParam1 = url.searchParams.has('param1'); // true
登入後複製
更改參數值:

添加參數,沒有頁面重新加載URLSearchParams.set()

>使用
let url = new URL("http://example.com/page?param1=value1&param2=value2");
url.searchParams.set('param1', 'newValue1');
登入後複製
>在沒有完整頁面刷新的情況下更新URL:

>

以上是jQuery添加參數到URL功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板