首页 > 语言 > JavaScript > 正文

javascript将相对路径转绝对路径示例

2024-05-06 14:28:25
字体:
来源:转载
供稿:网友

这里介绍的其实本质上是两种方法,通过创建DOM或通过JavaScript计算:

1)通过新创建的Image, 经测试会发送一个Aborted的请求,并且IE6不支持, 将new Image改成document.createElement('IMG')也是一样的;测试应该不喜欢这个方案;

代码如下:
function getAbsoluteUrl(url){
    var img = new Image();
    img.src = url;  // 设置相对路径给Image, 此时会发送出请求
    url = img.src;  // 此时相对路径已经变成绝对路径
    img.src = null; // 取消请求
    return url;
}
getAbsoluteUrl("showroom/list");

2)创建Anchor(链接),这种方法不会发出任何请求(请求会在加入DOM时产生),但是IE6也不支持

代码如下:
/*jslint regexp: true, white: true, maxerr: 50, indent: 2 */

function parseURI(url) {
  var m = String(url).replace(/^/s+|/s+$/g, '').match(/^([^://?#]+:)?(////(?:[^:@]*(?::[^:@]*)?@)?(([^://?#]*)(?::(/d*))?))?([^?#]*)(/?[^#]*)?(#[/s/S]*)?/);
  // authority = '//' + user + ':' + pass '@' + hostname + ':' port
  return (m ? {
    href     : m[0] || '',
    protocol : m[1] || '',
    authority: m[2] || '',
    host     : m[3] || '',
    hostname : m[4] || '',
    port     : m[5] || '',
    pathname : m[6] || '',
    search   : m[7] || '',
    hash     : m[8] || ''
  } : null);
}

function absolutizeURI(base, href) {// RFC 3986

  function removeDotSegments(input) {
    var output = [];
    input.replace(/^(/./.?(//|$))+/, '')
         .replace(///(/.(//|$))+/g, '/')
         .replace(////./.$/, '/../')
         .replace(///?[^//]*/g, function (p) {
      if (p === '/..') {
        output.pop();
      } else {
        output.push(p);
      }
    });
    return output.join('').replace(/^///, input.charAt(0) === '/' ? '/' : '');
  }

  href = parseURI(href || '');
  base = parseURI(base || '');

  return !href || !base ? null : (href.protocol || base.protocol) +
         (href.protocol || href.authority ? href.authority : base.authority) +
         removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选