Javascript 使用 jQuery 构造带参数的 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8902390/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:00:51  来源:igfitidea点击:

Constructing a URL with parameters using jQuery

javascriptjquery

提问by Alfredo Osorio

I have for example the following URL stored in a global variable:

例如,我将以下 URL 存储在全局变量中:

var myUrl = "http://mydomain.com/something?row=1";

Then a function has to add let's say another parameter called "column". How would that function add parameters to a pre-existing URL string using jQuery?

然后一个函数必须添加让我们说另一个名为“ column”的参数。该函数如何使用 jQuery 将参数添加到预先存在的 URL 字符串中?

Example of the expected generated string:

预期生成的字符串示例:

"http://mydomain.com/something?row=1&column=9"

The problem is that myUrlcould also be just:

问题是这myUrl也可能只是:

var myUrl = "http://mydomain.com/something";

(Notice that there are not pre-existing parameters)

(注意没有预先存在的参数)

采纳答案by Jesse Pollak

Check out the jQuery function .param(), that should do the trick.

查看 jQuery 函数 .param(),它应该可以解决问题。

http://api.jquery.com/jQuery.param/

http://api.jquery.com/jQuery.param/

You can then just create a function which appends the string generated by .param() to a url.

然后,您可以创建一个函数,将 .param() 生成的字符串附加到 url。

回答by epascarello

var myUrl = "http://mydomain.com/something";

function addQSParm(name, value) {
    var re = new RegExp("([?&]" + name + "=)[^&]+", "");

    function add(sep) {
        myUrl += sep + name + "=" + encodeURIComponent(value);
    }

    function change() {
        myUrl = myUrl.replace(re, "" + encodeURIComponent(value));
    }
    if (myUrl.indexOf("?") === -1) {
        add("?");
    } else {
        if (re.test(myUrl)) {
            change();
        } else {
            add("&");
        }
    }
}

console.log(myUrl);

addQSParm("foo", "asdf");
console.log(myUrl);

addQSParm("bar", "qwerty");
console.log(myUrl);

addQSParm("foo", "123");
console.log(myUrl);

jsFiddle

js小提琴

回答by Andrew Hare

You don't need jQuery, use a function like this:

你不需要 jQuery,使用这样的函数:

var buildUrl = function(base, key, value) {
    var sep = (base.indexOf('?') > -1) ? '&' : '?';
    return base + sep + key + '=' + value;
}

You would use it like this:

你会像这样使用它:

buildUrl('http://www.example.com/foo', 'test', '123');
buildUrl('http://www.example.com/foo?bar=baz', 'test', '123');

回答by Esailija

Keep everything in an object until you actually need a string.

将所有内容保存在一个对象中,直到您真正需要一个字符串为止。

First populate the object from some initial values:

首先从一些初始值填充对象:

var $_GET = location.search.substr(1).split("&").reduce( function( obj, val ){
    if( !val ) return obj;
    var pair = val.split("=");
    obj[pair[0]] = pair[1];
    return obj;
}, {} );

Considering initial url of: "http://mydomain.com/something?row=1&column=9"

考虑初始网址: "http://mydomain.com/something?row=1&column=9"

$_GET['column'] = 5;

$.param( $_GET ); //"row=1&column=5"

Array#reduce

数组#reduce

回答by ShankarSangoli

You can try this.

你可以试试这个。

myUrl += ((myUrl.indexOf('?') == -1) ? '?' : '&');
myUrl += "column=9";

回答by Omar Stewey

if (myUrl.indexOf("?") != -1){
    // contains query string
}
else
{
    // doesn't
}