是否有一种方法/功能来获取规范的/转换的URL,同时尊重页面的任何base.href设置?

我可以使用$("base").attr("href")通过(在jQuery中)获取基本URL,并且我可以使用字符串方法来解析要相对于此生成的URL,但是


$(“ base”)。attr(“ href”)没有主机,路径等属性(例如window.location具有)
手动将其放在一起相当乏味


例如,给定"http://example.com/foo/"的base.href和相对URL "/bar.js",结果应为:"http://example.com/bar.js"

如果不存在base.href,则应相对于window.location设置URL。
这应该处理不存在的base.href(在这种情况下,使用location作为基准)。

是否已经有标准方法可用于此?

(我正在寻找这个,因为当使用相对URL(例如“ /foo.js”)时jQuery.getScript失败,并且正在使用BASE标签(FF3.6发出OPTIONS请求,而nginx无法处理此问题。)完整网址(base.href.host +“ /foo.js”,可以正常工作。)

最佳答案

这能达到目的吗?

function resolveUrl(url){
    if (!url) {
        throw new Error("url is undefined or empty");
    }
    var reParent = /[\-\w]+\/\.\.\//, // matches a foo/../ expression
 reDoubleSlash = /([^:])\/\//g; // matches // anywhere but in the protocol
    // replace all // except the one in proto with /
    url = url.replace(reDoubleSlash, "$1/");
    var base = (document.getElementsByTagName('BASE')[0] && document.getElementsByTagName('BASE')[0].href) || "";

    // If the url is a valid url we do nothing
    if (!url.match(/^(http||https):\/\//)) {
        // If this is a relative path
        var path = (url.substring(0, 1) === "/") ? base : location.pathname;
        if (path.substring(path.length - 1) !== "/") {
            path = path.substring(0, path.lastIndexOf("/") + 1);
        }
        if (!url.match(/^(http||https):\/\//)) {
            url = location.protocol + "//" + location.host + path + url;
        }
    }

    // reduce all 'xyz/../' to just ''
    while (reParent.test(url)) {
        url = url.replace(reParent, "");
    }
    return url;
}


它是根据我之前的一些代码修改而成的,因此尚未经过测试

10-08 08:01
查看更多