2010-05-14 32 views
0

是否有方法/函數來獲取規範化/轉換的URL,尊重頁面的任何base.href設置?根據base.href或位置生成規範/真實URL

我可以用$("base").attr("href")獲得通過基本URL(jQuery的),我可以用字符串的方法來解析意味着是相對於本作的URL,但

  • $(「基地」)。ATTR (的「href」)不具有主機,路徑等屬性(象window.location的具有)
  • 手動把這個一起是相當乏味

例如,給定的一個"http://example.com/foo/"和base.href相對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」,它工作)。)

+0

在此期間,您是否找到更好的解決方案? – 2010-11-10 00:51:32

+0

不,不幸的不是。 – blueyed 2010-11-22 16:05:53

回答

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

它是由一些代碼,我不得不四處修改,所以它並沒有經過測試

+0

是的,這可能會訣竅。 但是,它至少不適用於「//example.com」(reDoubleSlash),我一直在尋找「含電池」類型的解決方案。 如果jQuery提供了這樣的功能,它可能已經足夠好了,它可能已經存在了,但是我找不到它。 – blueyed 2010-05-14 19:57:48