2011-10-04 29 views
1

Python有一個函數urljoin,它帶有兩個URL並將它們智能地連接起來。有沒有在AS3中提供類似功能的庫?在AS3中等效的Python urljoin

urljoin文檔:http://docs.python.org/library/urlparse.html

和Python例如:

>>> urljoin('http://www.cwi.nl/doc/Python.html', '../res/jer.png') 
'http://www.cwi.nl/res/jer.png' 

我想知道是否有urljoin功能,而不是整個urlparse

+3

你可以重寫HTTP://hg.python。 org/cpython/file/2.7/Lib/urlparse.py in AS3;) – Kodiak

+0

您是否正在尋找AS3中的完整python類功能,或者只是描述了基本url和相對url合併的功能? – Mattias

+0

@Mattias我編輯了這個問題。 –

回答

2

一些原始代碼做你想要什麼,所以你可以跳過所有的臃腫庫:

var urlJoin:Function = function(base:String, relative:String):String 
{ 
    // See if there is already a protocol on this 
    if (relative.indexOf("://") != -1) 
     return relative; 

    // See if this is protocol-relative 
    if (relative.indexOf("//") == 0) 
    { 
     var protocolIndex:int = base.indexOf("://"); 
     return base.substr(0, protocolIndex+1) + relative; 
    } 

    // We need to split the domain and the path for the remaining options 
    var protocolIndexEnd:int = base.indexOf("://") + 3; 
    if (base.indexOf("/", protocolIndexEnd) == -1) // append slash if passed only http://bla.com 
     base += "/"; 
    var endDomainIndex:int = base.indexOf("/", protocolIndexEnd); 
    var domain:String = base.substr(0, endDomainIndex); 
    var path:String = base.substr(endDomainIndex); 
    if (path.lastIndexOf("/") != path.length-1) // trim off any ending file name 
     path = path.substr(0, path.lastIndexOf("/")+1); 

    // See if this is site-absolute 
    if (relative.indexOf("/") == 0) 
    { 
     return domain + relative; 
    } 

    // See if this is document-relative with ../ 
    while (relative.indexOf("../") == 0) 
    { 
     relative = relative.substr(3); 
     if (path.length > 1) 
     { 
      var secondToLastSlashIndex:int = path.substr(0, path.length-1).lastIndexOf("/"); 
      path = path.substr(0, secondToLastSlashIndex+1); 
     } 
    } 
    // Finally, slap on whatever ending is left 
    return domain + path + relative; 
}; 
+0

我提出了兩個答案,但是我選擇你的答案是因爲你花費了代碼。謝謝! –

+0

更多代碼並不總是最好的答案。 – Joony

+0

是的。如果有人已經做出了你想要的,你不需要重新發明輪子。 – apscience

3

可以使用例如的實現URIas3corelib

用法:

import com.adobe.net.URI; 

// create uri you want to be updated 
var newURI:URI=new URI('../res/jer.png') 

// update newURI with the full path 
newURI.makeAbsoluteURI(new URI('http://www.cwi.nl/doc/Python.html')) 

trace(uri.toString()) // will output http://www.cwi.nl/res/jer.png 

// or make an utility function base on it: 

function urljoin(url1:string, url2:String):String { 
    var uri:URI=new URI(url2) 
    uri.makeAbsoluteURI(url1) 
    return uri.toString() 
}