使用查询参数重建URL

时间:2015-11-24 10:48:58

标签: javascript jquery

我有一个网址:

http://www.example.com/gclid/YH67/utm/2908321/id/test

我想使用查询参数的网址:

http://www.example.com/?gclid=YH67&utm=2908321&id=test

我所知道的是主网址http://www.example.com/

我想让url拥有正确的参数(我不知道key / value的具体参数)。

这是一个我看到它有效的简单例子

if (window.location.href === "http://www.example.com") { 
   url = "http://www.example.com?gclid=test"; 
   window.history.pushState("", "", url); 
}

2 个答案:

答案 0 :(得分:3)

尝试这个 -

from django.http import HttpResponse

class ArticleFeed(Feed):
    "snip [standard definitions of title, link, methods...]"

    def __call__(self,request,*args,**kwargs):
        if not request.user.is_authenticated():
            return HttpResponse(status=401)
        else:
            return super().__call__(request,*args,**kwargs)

像这样调用上面的函数 - function makeURL(url) { var mainUrl = "http://www.example.com/"; var urlArr = url.split(mainUrl); if(urlArr[1] && urlArr[1] !== "") { // assuming url will always be a perfect url var queryPoints = urlArr[1].split("/"); var queryStr = "?"; for(var i = 0; i < queryPoints.length; i+=2) { var key = queryPoints[i]; var value = queryPoints[i+1]; if(i+2 == queryPoints.length) queryStr += key+ "=" + value; else queryStr += key+ "=" + value + "&"; } var queriedUrl = mainUrl + queryStr; console.log(queriedUrl); return queriedUrl; } return url; } 。它将以查询字符串格式返回数据。

答案 1 :(得分:0)

以下是使用查询字符串将给定网址转换为网址的更新:

&#13;
&#13;
var url='http://www.example.com/gclid/YH67/utm/2908321/id/test';
var domain='http://www.example.com/';

function extractParams(url,domain) {
    var params=url.replace(domain,'').split('/');
    var newparams={};
    for (var i=0;i<params.length;i=i+2) {
        newparams[params[i]]=params[i+1];
    }
    
    return newparams;
}

function httpBuildQuery(params) {
	var query=[];
    for (var key in params) {
     	query.push(key+'='+params[key]);   
    }
    
    return query.join('&');
}

console.log(httpBuildQuery(extractParams(url,domain)));
&#13;
&#13;
&#13;