最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

string - How to pass 2 JavaScript variables through a url? - Stack Overflow

programmeradmin3浏览0评论

I am trying to have 2 variable values passed in a url, which url will be redirected after. How can I insert them in a JavaScript string?

I have:

var a = document.getElementById("username_a").value;
var b = document.getElementById("username_b").value;

and want something like: var string_url = "/?{a}blabla={b}" and then redirect somehow.

In PHP I would go with that code for example: <iframe src="=<?php echo $the_variable;?>">

I am trying to have 2 variable values passed in a url, which url will be redirected after. How can I insert them in a JavaScript string?

I have:

var a = document.getElementById("username_a").value;
var b = document.getElementById("username_b").value;

and want something like: var string_url = "http://www.example./?{a}blabla={b}" and then redirect somehow.

In PHP I would go with that code for example: <iframe src="http://www.example.?query=<?php echo $the_variable;?>">

Share Improve this question edited Jan 7, 2012 at 11:49 Matteo B. 4,0742 gold badges34 silver badges43 bronze badges asked Jan 7, 2012 at 11:26 a.litisa.litis 4433 gold badges12 silver badges24 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

You can add strings in JavaScript, "a" + "b" == "ab" evaluates to true.

So what you want is probably var string_url = "http://www.example./?" + a + "&blabla=" + b;

But you should ever escape vars especially if they e from inputs, so try

a = encodeURIComponent(a);
b = encodeURIComponent(b);

And then

var string_url = "http://www.example./?" + a + "&blabla=" + b;

To redirect you can use window.location:

window.location = string_url;

use the ampersand to split vars

var string_url = "http://www.example./?" + "username_a=" + a + "&username_b=" + `b

Could be made more sopisticated, but that in essence is what you need

JavaScript doesn't do string interpolation. You have to concatenate the values.

var uri = "http://example./?" + encodeUriComponent(name_of_first_variable) + "=" + encodeUriComponent(value_of_first_variable) + '&' + encodeUriComponent(name_of_second_variable) + "=" + encodeUriComponent(value_of_second_variable);
location.href = uri;
发布评论

评论列表(0)

  1. 暂无评论