请问在通过 jquery get 加载的页面内如何获取当前的 url 地址?

我有个页面弹窗,是在 index.html 页面加载的 js 代码里通过 jquery get 方法实现的,大概代码如下:

$.get('./addOrEdit.html?id=100', function (data) {
            var info = data, oppoBox = $('#oppoBox'), title = $.trim(obj.attr('atitle'));
            if (info.length) {
                $('#oppoInfo').html(info);
                $('#oppoBg').css({'height': $(document).outerHeight() + 'px'});
                oppoBox.css({'width': $(document).outerWidth() * 11 / 18 + 'px'});
                var top = $(window).height() / 18, height = $(window).height() - top * 2;
                oppoBox.css({
                    'left': ($(document).outerWidth() - oppoBox.outerWidth()) / 2 + 'px',
                    'top': top + 'px',
                    'height': height + 'px',
                    'overflow': 'hidden'
                });
                $('#oppoTitle').text(title);
                $('#oppoInfo').css({
                    'height': height - parseInt($('#toolBar').css('lineHeight')) - parseInt($('#oppoInfo').css('paddingTop')) - parseInt($('#oppoInfo').css('paddingBottom')) + 'px'
                });
                $('#oppoBg,#oppoBox').removeClass('hide');
            }
        });

现在我期望是在 addOrEdit.html?id=100 页面加载的 js 文件获取到当前的 id 的参数值,但是现在获取到的当前页面地址一直是 index.html,请问大神这个该怎么办?小弟跪谢。

请大佬不要告诉直接写死 100 就行了,我这里为了方便看直接写成了 addOrEdit.html?id=100,实际的页面这个 url 是个变量表示的。

阅读 1.3k
avatarAI BotBETA

你可以使用 JavaScript 的 window.location 对象来获取当前页面的 URL。然后,你可以使用 split 函数和 URLSearchParams 对象来解析 URL 中的参数。下面是一个示例代码:

// 获取当前页面的 URL
var currentUrl = window.location.href;

// 解析 URL 中的参数
var params = new URLSearchParams(currentUrl);

// 获取 id 参数的值
var id = params.get('id');

console.log(id); // 输出 "100"

在这个示例中,window.location.href 用于获取当前页面的完整 URL。然后,new URLSearchParams(currentUrl) 用于创建一个新的 URLSearchParams 对象,该对象包含 URL 中的查询参数。最后,params.get('id') 用于获取名为 "id" 的参数的值。在这个例子中,输出将是 "100"。

请注意,这个方法适用于任何页面,包括通过 AJAX 或其他方式加载的页面。无论页面是如何加载的,window.location.href 总是返回当前页面的完整 URL。

3 个回答

addOrEdit.html?id=100 页面加载的 js 文件为什么能够执行,是因为调用了 html() 方法,该方法底层是使用 window.eval() 来执行脚本的,window.eval 是一种 eval 的间接调用方式,会在全局环境下执行代码,也就是 js 文件执行的环境就是当前页面 index.html 下的全局环境。所以只需要把 id 值存储为一个全局变量就可以被获取了。

你是怎么获取的id参数值,能给出具体代码吗

将页面地址存放在url的hash上面。类似路由的做法,但不能同时设置多个hash,不然找不到路径。


let htmlUrl = './addOrEdit.html?id=100';
util.setUrlHash(htmlUrl);
$.get(htmlUrl, function (data) {
            var info = data, oppoBox = $('#oppoBox'), title = $.trim(obj.attr('atitle'));
            if (info.length) {
                $('#oppoInfo').html(info);
            }
        });

addOrEdit.html 优先获取hash的参数,如果没有hash,则获取url的参数。

let hash = util.getUrlHash();
let locationObj = util.getLocation(hash, location);
let params = util.getUrlParams(locationObj.search);
let id = params.id;
console.log(params.id);
const util = {
    /**
     * 获取当前url
     * @returns {URL}
     * @param href
     */
    getLocation: (url = window.location, base = window.origin) => {
        // 把键值对列表转换为一个对象
        return new URL(url, base);
    },
    /**
     * 设置当前url 哈希
     * @returns {string}
     */
    setUrlHash: (hash = window.location.hash) => {
        return window.location.hash = hash;
    },
    /**
     * 获取当前url 哈希
     * @returns {string}
     */
    getUrlHash: (hash = window.location.hash) => {
        return hash.replace('#', '');
    },
    /**
     * 获取当前url参数
     * @returns {{[p: string]: string}}
     * @param search
     */
    getUrlParams: (search = window.location.search) => {
        // 创建一个URLSearchParams实例
        const urlSearchParams = new URLSearchParams(search);
        // 把键值对列表转换为一个对象
        return Object.fromEntries(urlSearchParams.entries());
    },
    /**
     * 设置当前url参数
     * @returns {{[p: string]: string}}
     * @param search
     */
    setUrlParams: (search = window.location.search) => {
        return window.location.search = search;
    },
    /**
     * 对象转url参数
     * @param name
     * @returns {{[p: string]: string}}
     */
    toUrlParams: (obj = {}) => {
        // 创建一个URLSearchParams实例
        var searchParams = new URLSearchParams();
        // 把对象转换为一个url参数
        Object.entries(obj).forEach(param => searchParams.append(...param));
        return searchParams.toString();
    }
}

JS API 可看具体兼容性要求
https://developer.mozilla.org/zh-CN/docs/Web/API/URL

https://developer.mozilla.org/zh-CN/docs/Web/API/URLSearchParams

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Refer...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题