Javascript jQuery 将参数附加到 url
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28629648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery append params to url
提问by Karolis
I like the way jQuery's $.ajax() method allows to specify request url:
我喜欢 jQuery 的 $.ajax() 方法允许指定请求 url 的方式:
{
url: 'http://domain.com/?param=1',
data{
param2: '2'
}
}
$.ajax() method will (probably) call $.param() on provided data and optionally append it to provided URL.
$.ajax() 方法将(可能)在提供的数据上调用 $.param() 并可选择将其附加到提供的 URL。
My question is: is this type of url manipulation available outside of $.ajax() call?
我的问题是:在 $.ajax() 调用之外是否可以使用这种类型的 url 操作?
For example, I want to open a popup window, and I would like to construct URL in the same way that I do with $.ajax().
例如,我想打开一个弹出窗口,我想以与 $.ajax() 相同的方式构造 URL。
I have written a function which does this, but I have a feeling I am reinventing the wheel and duplicating already existing function of jQuery:
我已经编写了一个函数来执行此操作,但我有一种感觉,我正在重新发明轮子并复制 jQuery 已经存在的函数:
var prepareUrl = function( url, data )
{
var params = $.param( data );
if ( params.length > 0 )
{
// url contains a query string
if ( url.indexOf( '?' ) > -1 )
{
// get last char of url
var lastChar = url.substr( url.length - 1 );
// Append & to the end of url if required
if ( lastChar != '&' && lastChar != '?' )
{
url += '&';
}
}
else // url doesn't contain a query string
{
url += '?';
}
url += params;
}
return url;
}
thanks!
谢谢!
采纳答案by Karolis
Since other replies didn't answer my question, i have made a few tests with the $.ajax()call to see how it merges urls with param data.
由于其他回复没有回答我的问题,我对$.ajax()调用进行了一些测试,以查看它如何将 url 与参数数据合并。
My findings so far:
到目前为止我的发现:
- if url contains a
?, then$.ajax()will append'&'+$.param(data) - if not, then
$.ajax()will append'?'+$.param(data)
- 如果 url 包含 a
?,$.ajax()则将附加'&'+$.param(data) - 如果没有,那么
$.ajax()将附加'?'+$.param(data)
So if I want to keep my url processing function consistent with the way $.ajax()does it, then it should be something like the following:
所以如果我想让我的 url 处理函数与$.ajax()它的方式保持一致,那么它应该是这样的:
var addParams = function( url, data )
{
if ( ! $.isEmptyObject(data) )
{
url += ( url.indexOf('?') >= 0 ? '&' : '?' ) + $.param(data);
}
return url;
}
I am still wondering if there is a built-in jQuery method to do this.
我仍然想知道是否有一个内置的 jQuery 方法来做到这一点。
回答by Shreejibawa
You can build query stringlike this:
您可以像这样构建查询字符串:
getQueryStr = function(obj) {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
console.log(serialize({
param1: "val1",
param2: "val2"
}));
For recursive :
对于递归:
getQueryStr = function(obj, prefix) {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p,
v = obj[p];
str.push(typeof v == "object" ?
getQueryStr(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
}
console.log(serialize({
favfruit: "apple",
data: {
name: 'js',
points: [1, 2, 3]
}
}));
回答by kasper Taeymans
yes you can use jqueries .param()function to do this.
是的,您可以使用 jquery.param()函数来执行此操作。
var params = { param1:"foo", param2:"bar"};
var str = jQuery.param( params );
alert(str);
回答by Quentin
The parammethod will generate a query string for you, but you will need to to remove the existing query string.
该param方法将为您生成一个查询字符串,但您需要删除现有的查询字符串。
var base = "http://example.com/foo/?example=old";
var data = {
foo: "hello",
bar: "world?"
};
var url = base.replace(/\?.*$/, "") + "?" + jQuery.param(data);
alert(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

