在AS3中等效的Python urljoin

时间:2011-10-04 14:24:03

标签: python actionscript-3 url

Python有一个函数urljoin,它接受两个URL并智能地连接它们。是否有一个在AS3中提供类似功能的库?

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

2 个答案:

答案 0 :(得分:3)

您可以使用URI

中的as3corelib

用法:

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()
}

答案 1 :(得分: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;
};