如何使用参数检索整个URL
How to retrieve the whole URL with parameters?
我需要检索整个URL,并将参数作为字符串。例如,我需要检索以下URL:
http://www.keytometals.com/page.aspx?ID=CheckArticle&site=kts&LN=EN&NM=349
我试过使用:
document.location.href,
document.URL,
window.location.href
但它只检索URL的一部分:
http://www.keytometals.com/page.aspx
如何获取包含当前URL及其参数的字符串?
更新:我使用了
window.content.document.location.href
我得到了以下URL:
http://www.keytometals.com/page.aspx?ID=CheckArticle
不幸的是,它仍然是URL的一部分。有人能帮我如何将整个URL作为字符串吗?
谢谢!
您应该对整个URL(包括查询字符串)使用window.location.href
。
查看Mozilla的文档以了解更多信息和其他属性。
下面是另一篇关于如何用JavaScript解析查询字符串的好文章StackOverflow。
您只需要简单的document.location
——它将包括所有内容。您需要编写自己的代码才能在?只获取查询字符串,然后在每个&处将其拆分为名称/值对;。
编辑:
实际上,您也可以使用location.search
。这是我为此写的一个片段:
function loadQueryString(){
var parameters = {};
var searchString = location.search.substr(1);
var pairs = searchString.split("&");
var parts;
for(i = 0; i < pairs.length; i++){
parts = pairs[i].split("=");
var name = parts[0];
var data = decodeURI(parts[1]);
parameters[name] = data;
}
return parameters;
}
params = loadQueryString();
function getQueryString() {
var key = false, res = {}, itm = null;
// get the query string without the ?
var qs = location.search.substring(1);
// check for the key as an argument
if (arguments.length > 0 && arguments[0].length > 1)
key = arguments[0];
// make a regex pattern to grab key/value
var pattern = /([^&=]+)=([^&]*)/g;
// loop the items in the query string, either
// find a match to the argument, or build an object
// with key/value pairs
while (itm = pattern.exec(qs)) {
if (key !== false && decodeURIComponent(itm[1]) === key)
return decodeURIComponent(itm[2]);
else if (key === false)
res[decodeURIComponent(itm[1])] = decodeURIComponent(itm[2]);
}
return key === false ? res : null;
}
然后你这样使用它:
// get a single key (if it exists)
var t = getQueryString('site');
console.log(t);
// get the whole thing as an object
t = getQueryString();
console.log(t);
相关文章:
- JQuery:从URL检索数据
- 要从 URL 检索的正则表达式
- 如何从 URL 检索第一个 H1
- 从 URL 检索和显示 JSON 数据
- JQuery AJAX-如何从URL检索JSON数据
- 两个javascript函数,第二个等待第一个使用getScript从外部URL检索值
- 从 javascript 中的 URL 检索 ID 参数
- javascript为url检索表单数据时出现问题
- 从URL检索对象/资源
- 如何从Blob url检索MediaStream
- 通过jQueryAJAX从远程URL检索JSON数据
- 解析从json中的url检索到的响应
- 试图用HTML5文件系统将画布PNG数据url保存到磁盘,但当我作为url检索时,它's无效
- 用从某个URL检索到的数据替换整个html-body内容
- Javascript -如何“请求查询字符串”从Url.检索参数值的操作链接
- 使用javascript从url检索特定链接
- 当需要从URL检索数据时,AJAX在浏览器中不起作用
- Facebook json url检索事件墙饲料
- Jquery/Javascript URL检索不起作用
- 无法使用javascript从html页面中的url检索JSON数据