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
方法就在JS代碼里先創建一個a標簽然後將需要解析的URL賦值給a的href屬性
利用這一原理,稍微擴展一下,就得到了一個更加健壯的解析URL各部分的通用方法
代碼:
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"));方法二:字元串截取法調用:調用方法: