导航:首页 > 编程语言 > js分析url

js分析url

发布时间:2023-03-09 15:03:39

1. 前端使用js如何准确获取当前页面url网址信息

在WEB开发中,时常会用到javascript来获取当前页面的url网址信息,在这里是我的一些获取url信息的小总结。

下面我们举例一个URL,然后获得它的各个组成部分:http://i.cnblogs.com/EditPosts.aspx?opt=1

1、window.location.href(设置或获取整个 URL 为字符串)

var test = window.location.href;

alert(test);

返回:http://i.cnblogs.com/EditPosts.aspx?opt=1

2、window.location.protocol(设置或获取 URL 的协议部分)

var test = window.location.protocol;

alert(test);

返回:http:

3、window.location.host(设置或获取 URL 的主机部分)

var test = window.location.host;

alert(test);

返回:i.cnblogs.com

4、window.location.port(设置或获取与 URL 关联的端口号码)

var test = window.location.port;

alert(test);

返回:空字符(如果采用默认的80端口(update:即使添加了:80),那么返回值并不是默认的80而是空字符)

5、window.location.pathname(设置或获取与 URL 的路径部分(就是文件地址))

var test = window.location.pathname;

alert(test);

返回:/EditPosts.aspx

6、window.location.search(设置或获取 href 属性中跟在问号后面的部分)

var test = window.location.search;

alert(test);

返回:?opt=1

PS:获得查询(参数)部分,除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值。

7、window.location.hash(设置或获取 href 属性中在井号“#”后面的分段)

var test = window.location.hash;

alert(test);

返回:空字符(因为url中没有)

8、js获取url中的参数值

一、正则法

function getQueryString(name) {  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');  var r = window.location.search.substr(1).match(reg);  if (r != null) {    return unescape(r[2]);  }  return null;}// 这样调用:alert(GetQueryString("参数名1"));  alert(GetQueryString("参数名2"));  alert(GetQueryString("参数名3"));

二、split拆分法

function GetRequest() {

  var url = location.search; //获取url中"?"符后的字串

  var theRequest = new Object();

  if (url.indexOf("?") != -1) {

    var str = url.substr(1);

    strs = str.split("&");

    for(var i = 0; i < strs.length; i ++) {

      theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);

    }

  }

  return theRequest;

}

var Request = new Object();

Request = GetRequest();<br>// var id=Request["id"];

// var 参数1,参数2,参数3,参数N;

// 参数1 = Request['参数1'];

// 参数2 = Request['参数2'];

// 参数3 = Request['参数3'];

// 参数N = Request['参数N'];

三、指定取

比如说一个url:http://i.cnblogs.com/?j=js,我们想得到参数j的值,可以通过以下函数调用。

function GetQueryString(name) {

  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");

  var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配

  var context = "";

  if (r != null)

    context = r[2];

  reg = null;

  r = null;

  return context == null || context == "" || context == "undefined" ? "" : context;

}

alert(GetQueryString("j"));

四、单个参数的获取方法

function GetRequest() {

  var url = location.search; //获取url中"?"符后的字串

  if (url.indexOf("?") != -1) {  //判断是否有参数

  var str = url.substr(1); //从第一个字符开始 因为第0个是?号 获取所有除问号的所有符串

  strs = str.split("=");  //用等号进行分隔 (因为知道只有一个参数 所以直接用等号进分隔 如果有多个参数 要用&号分隔 再用等号进行分隔)

  alert(strs[1]);    //直接弹出第一个参数 (如果有多个参数 还要进行循环的)

  }

}

一、正则法

functiongetQueryString(name) {

  varreg = newRegExp('(^|&)'+ name + '=([^&]*)(&|$)', 'i');

  varr = window.location.search.substr(1).match(reg);

  if(r != null) {

    returnunescape(r[2]);

  }

  returnnull;

}

// 这样调用:

alert(GetQueryString("参数名1"));

alert(GetQueryString("参数名2"));

alert(GetQueryString("参数名3"));

二、split拆分法

functionGetRequest() {

  varurl = location.search; //获取url中"?"符后的字串

  vartheRequest = newObject();

  if(url.indexOf("?") != -1) {

    varstr = url.substr(1);

    strs = str.split("&");

    for(vari = 0; i < strs.length; i ++) {

      theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);

    }

  }

  returntheRequest;

}

varRequest = newObject();

Request = GetRequest();<br>// var id=Request["id"];

// var 参数1,参数2,参数3,参数N;

// 参数1 = Request['参数1'];

// 参数2 = Request['参数2'];

// 参数3 = Request['参数3'];

// 参数N = Request['参数N'];

三、指定取

比如说一个url:http://i.cnblogs.com/?j=js,我们想得到参数j的值,可以通过以下函数调用。

functionGetQueryString(name) {

  varreg = newRegExp("(^|&)"+ name + "=([^&]*)(&|$)", "i");

  varr = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配

  varcontext = "";

  if(r != null)

     context = r[2];

  reg = null;

  r = null;

  returncontext == null|| context == ""|| context == "undefined"? "": context;

}

alert(GetQueryString("j"));

四、单个参数的获取方法

functionGetRequest() {

  varurl = location.search; //获取url中"?"符后的字串

  if(url.indexOf("?") != -1) {  //判断是否有参数

   varstr = url.substr(1); //从第一个字符开始 因为第0个是?号 获取所有除问号的所有符串

   strs = str.split("=");  //用等号进行分隔 (因为知道只有一个参数 所以直接用等号进分隔 如果有多个参数 要用&号分隔 再用等号进行分隔)

   alert(strs[1]);     //直接弹出第一个参数 (如果有多个参数 还要进行循环的)

  }

}

2. js如何解析url

  1. 方法就在JS代码里先创建一个a标签然后将需要解析的URL赋值给a的href属性

  2. 利用这一原理,稍微扩展一下,就得到了一个更加健壮的解析URL各部分的通用方法

  3. 代码:


    function parseURL(url) {
    var a = document.createElement('a');
    a.href = url;
    return {
    source: url,
    protocol: a.protocol.replace(':',''),
    host: a.hostname,
    port: a.port,
    query: a.search,
    params: (function(){
    var ret = {},
    seg = a.search.replace(/^?/,'').split('&'),
    len = seg.length, i = 0, s;
    for (;i<len;i++) {
    if (!seg[i]) { continue; }
    s = seg[i].split('=');
    ret[s[0]] = s[1];
    }
    return ret;
    })(),
    file: (a.pathname.match(//([^/?#]+)$/i) || [,''])[1],
    hash: a.hash.replace('#',''),
    path: a.pathname.replace(/^([^/])/,'/$1'),
    relative: (a.href.match(/tps?://[^/]+(.+)/) || [,''])[1],
    segments: a.pathname.replace(/^//,'').split('/')
    };
    }
    用法

    var myURL = parseURL('htt p:/ /abc.com:8080/dir/inde x.h tml?id=255&m=hello#top');

    myURL.file; // = 'index.html'
    myURL.hash; // = 'top'
    myURL.host; // = 'abc.com'
    myURL.query; // = '?id=255&m=hello'
    myURL.params; // = Object = { id: 255, m: hello }
    myURL.path; // = '/dir/index.html'
    myURL.segments; // = Array = ['dir', 'index.html']
    myURL.port; // = '8080'
    myURL.protocol; // = 'http'

    myURL.source; // = 'htt p:/ /abc.com:8080/dir/index.h tml?id=255&m=hello#top'

3. 如何用js获取当前url的参数值

用js代码在本地分析来得到classid和自id的值总归是比较麻烦,而作为GET参数,在服务端总是要用到的。
如果你的本地js将用到这两个参数值,你可以直接让服务端将这两个值写入到本地。
<?php
$mystr="<script>x_classid=9;x_id=2</script>"
echo $mystr
?>
这样你在本地就可以直接调用x_classid和x_id以得到这两个参数。

4. JS获取地址栏url参数

本章内容分为三部分:

开始之前先简单了解一下

如:url地址: http://xxxxx:9010/test.html?leaf&le=2
window.location.search获取到的就是 ?leaf&le=2 ;
window.location.search.substr(1)获取到的就是 leaf&le=2 ;

一、JS获取地址栏url参数:

如果你想获取地址栏的其他参数,只需要执行 var 参数=getUrlParam('参数') ;
比如获取参数a,执行 var a=getUrlParam('a') 就可以啦。简单又实用。

二、解决请求接口乱码问题
但是在我请求接口数据的时候,页面获取到是类似???这种乱码。

然后我是这样解决的:
1、发送方decodeURI编码:

2、接收方encodeURI解码
根据后台接口拼接url中使用encodeURI:

三、关于根据后台接口拼接url

整理笔记,不断优化更新。如果有错误或可以优化的地方欢迎指出,互相学习,共同进步。
如果对你有用就点个小心心吧❤

5. JS对URL字符串进行编码/解码分析

虽然escape()、encodeURI()、encodeURIComponent()三种方法都能对一些影响URL完整性的特殊
字符进行过滤。但后两者是将字符串转换为UTF-8的方式来传输,解决了页面编码不一至导致的乱码问
题。例如:发送页与接受页的编码格式(Charset)不一致(假设发送页面是GB2312而接收页面编码是
UTF-8),使用escape()转换传输中文字串就会出现乱码问题。
以下是JS下对URL进行编/解码的各种方法:
escape
方法:返回一个可在所有计算机上读取的编码
String
对象。
function
escape(charString
:
String)
:
String
不会被此方法编码的字符:
@
*
/
+
说明:escape
方法返回一个包含
charstring
内容的字符串值(Unicode
格式)。所有空格、标点、
重音符号以及任何其他非
ASCII
字符都用
%xx
编码替换,其中
xx
等于表示该字符的十六进制数。
例如,空格返回为“%20”。(字符值大于
255
的字符以
%uxxxx
格式存储。)
注意:escape
方法不能用来对“统一资源标识符”(URI)
进行编码。对其编码应使用
encodeURI

encodeURIComponent
方法。
encodeURI
方法:返回编码为有效的统一资源标识符
(URI)
的字符串。
function
encodeURI(URIString
:
String)
:
String
不会被此方法编码的字符:!
@
#
$
&
*
(
)
=
:
/
;
?
+
'
说明:encodeURI
方法返回一个已编码的
URI。如果将编码结果传递给
decodeURI,则将返回初始的
字符串。encodeURI
不对下列字符进行编码:“:”、“/”、“;”和“?”。请使用
encodeURIComponent
对这些字符进行编码。
encodeURIComponent
方法:返回编码为统一资源标识符
(URI)
的有效组件的字符串。
function
encodeURIComponent(encodedURIString
:
String)
:
String
不会被此方法编码的字符:!
*
(
)
'
说明:encodeURIComponent
方法返回一个已编码的
URI。如果将编码结果传递给
decodeURIComponent,则将返回初始的字符串。因为
encodeURIComponent
方法将对所有字符编码,
请注意,如果该字符串代表一个路径,例如
/folder1/folder2/default.html,则其中的斜杠也将被
编码,这样,当该字符串作为请求发送到
Web
服务器时它将是无效的。如果字符串中包含多个
URI
组件,请使用
encodeURI
方法进行编码。
unescape
方法:从用
escape
方法编码的
String
对象中返回已解码的字符串。
function
unescape(charString
:
String)
:
String
说明:unescape
方法返回一个包含
charstring
内容的字符串值。所有以
%xx
十六进制形式编码的
字符都用
ASCII
字符集当中等效的字符代替。(以
%uxxxx
格式(Unicode
字符)编码的字符用十六
进制编码
xxxx

Unicode
字符代替。)
注意:unescape
方法不应用于解码“统一资源标识符”(URI)。请改用
decodeURI

decodeURIComponent
方法。
decodeURI
方法:返回一个已编码的统一资源标识符
(URI)
的非编码形式。
function
decodeURI(URIstring
:
String)
:
String
decodeURIComponent
方法:返回统一资源标识符
(URI)
的一个已编码组件的非编码形式。
function
decodeURIComponent(encodedURIString
:
String)
:
String
BTW:C#中对URL编码的方法。。。
编码:Server.UrlEncode(string)
解码:Server.UrlDecode(string)
前面三种客户端编码都可以用这个方法在后台解码。

6. js 判断指定的url是否有效(能访问)

<htmlxmlns="">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=gb2312"/>
<metaname="keywords"content="js判断URL是否可访问"/>
<title>js判断URL是否可访问</title>
</head>
<body>
<div>检验的url地址:</div>
<inputtype="text"style="width:600px;height:30px;font-size:14px;"id="urlText"value=""/>
<inputtype="button"value="判断是否可访问"onclick="getURL()"/>
<br/>
<divid="msg1"></div>
<divid="msg"></div>
<scripttype="text/javascript"src="js/jquery-1.10.2.js"></script>
<scripttype="text/javascript">
functiongetURL(){
$("#msg").html("");
varurl=$("#urlText").val();//请求的url
vardateTime=disptime();
vartime2=dateTime.DateTime;
$("#msg1").html("发送时间:"+time2);
$.ajax({
type:'get',
url:url,
cache:false,
dataType:"jsonp",//跨域采用jsonp方式
processData:false,
timeout:10000,//超时时间,毫秒
complete:function(data){
vardateTime2=disptime();
vartime22=dateTime2.DateTime;
varhtmlTxt=[];
if(data.status==200){
htmlTxt.push("成功<br/>");
}else{
htmlTxt.push("失败<br/>");
}
htmlTxt.push("readyState="+data.readyState+"<br/>status="+data.status+"<br/>statusText="+data.statusText+"<br/>响应时间:"+time22);
varhtmlString=htmlTxt.join('');
$("#msg").html(htmlString);
}
});
}
functiondisptime(){
vardate=newDate();
var=date.getFullYear();//四位年份
varmonth=date.getMonth()+1;//月份0-11
varday=date.getDate();//日
varHH=date.getHours();//时
varminute=date.getMinutes();//分钟
varsecond=date.getSeconds();//秒
varmilliseconds=date.getMilliseconds();//毫秒
if(month<10){
month="0"+month;
}
if(day<10){
day="0"+day;
}
if(HH<10){
HH="0"+HH;
}
if(minute<10){
minute="0"+minute;
}
if(second<10){
second="0"+second;
}
vartime=+"-"+month+"-"+day+""+HH+":"+minute+":"+second+""+milliseconds;
vartimeTxt=+month+day+HH+minute+second;
vartime={
DateTime:time,
TimeTxt:timeTxt
}
returntime;
}
</script>
</body>
</html>

7. 求一个用js读取url的方法

<script language=javascript>
var URLParams = new Object() ;
var aParams = document.location.search.substr(1).split('&') ;
for (i=0 ; i < aParams.length ; i++) {
容var aParam = aParams[i].split('=') ;
URLParams[aParam[0]] = aParam[1] ;
}

var sLinkFieldName = URLParams["id"] ;
var sExtCSS = URLParams["extcss"] ;
var sFullScreen = URLParams["fullscreen"];
</script>

8. 如何用js获取浏览器URL中查询字符串的参数

两种方法:方法一:正则分析法参考代码:functiongetQueryString(name){varreg=newRegExp("(^|&)"+name+"=([^&]*)(&|$)","i");varr=window.location.search.substr(1).match(reg);if(r!=null)returnunescape(r[2]);returnnull;}调用方法:alert(GetQueryString("参数名1"));alert(GetQueryString("参数名2"));方法二:字符串截取法调用:调用方法:

阅读全文

与js分析url相关的资料

热点内容
发文件给同事怎么说 浏览:468
苹果80岁用什么app 浏览:28
顺丰寄快递文件多少钱 浏览:164
消费邦app是怎么反现的 浏览:112
java调用接口方法 浏览:742
微信一种以上绑定关系 浏览:183
word图片编辑大小边框 浏览:468
威迅java培训 浏览:389
linux禅道无法访问 浏览:819
怎么爬取历史疫情数据 浏览:596
linuxjira6破解 浏览:694
哪个网站可以看所有检察杂志 浏览:144
java高并发数据库请求怎么办 浏览:551
win8怎么打开gho文件怎么打开 浏览:732
如何网站内搜索 浏览:362
qq附近的人客服号码 浏览:570
mac怎么把word文件转换为pdf 浏览:6
正式文件中的文档行距多少 浏览:202
vu用upload上传excel文件 浏览:544
win10m装安卓软件 浏览:83

友情链接