0

ページの base.href 設定を尊重して、正規/変換された URL を取得するメソッド/関数はありますか?

(jQuery で) を使用してベース URL を取得$("base").attr("href")できます。文字列メソッドを使用して、これに対して相対的に作成されることを意図した URL を解析できますが、

  • $("base").attr("href") にはホスト、パスなどの属性がありません (window.location のように)
  • 手動でこれをまとめるのはかなり面倒です

たとえば、 base.href"http://example.com/foo/"と相対 URLを指定すると"/bar.js"、結果は次のようになります。"http://example.com/bar.js"

base.href が存在しない場合、URL は window.location を基準にして作成する必要があります。これは、存在しない base.href を処理する必要があります (この場合、場所をベースとして使用します)。

これに利用できる標準的な方法はすでにありますか?

(「/foo.js」のような相対 URL を使用し、BASE タグが使用されていると jQuery.getScript が失敗するため、これを探しています (FF3.6 は OPTIONS 要求を作成し、nginx はこれを処理できません)。完全な URL (base.href.host + "/foo.js" で動作します)。

4

2 に答える 2

2

これでうまくいきますか?

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;
}

私が持っていたいくつかのコードから変更されているため、テストされていません

于 2010-05-14T17:36:19.890 に答える
0

js-uriは、これを実現するための便利なjavascriptライブラリです:http ://code.google.com/p/js-uri/

base.hrefとwindow.locationの部分を処理する必要がありますが、残りはライブラリを使用して実行できます。

于 2012-01-13T18:34:05.530 に答える