简体   繁体   English

Javascript 如何使用 window.open 将变量传递给 URL 查询

[英]Javascript how to pass variable to URL query with window.open

First of all - this question has no answers at Include variable in URL or How can I do string interpolation in JavaScript?首先 - 这个问题在 URL 中包含变量如何在 JavaScript 中进行字符串插值时没有答案? I tested many variants from elsewhere before my question here.在我在这里提出问题之前,我测试了其他地方的许多变体。 For example, as advised at Include variable in URL例如,按照在 URL 中包含变量的建议

window.open('http://example.com/?q="+ myname"');

does not work with the script below.不适用于下面的脚本。 A kind of specific wrapping is needed.需要一种特定的包装。

So, simplest script所以,最简单的脚本

<script type="text/javascript">
function sendquery() {
var myname = "John";
alert(myname);
window.open('http://example.com/?q=(myname)');
}
</script>
<button onclick="sendquery()">Query</button>

Alert perfectly shows variable John.警报完美地显示了变量 John。 But query sends not variable John but (myname).但是查询发送的不是变量 John,而是(myname)。

Or + myname - if follow other answers.或 + myname - 如果遵循其他答案。

How to wrap variable to URL query?如何将变量包装到 URL 查询?

It looks like you're just putting the variable in the string incorrectly.看起来您只是将变量错误地放入字符串中。 Check out template literals if you don't need to support IE.如果您不需要支持 IE,请查看模板文字


var myname = "John";
// won't work
window.open('http://example.com/?q="+ myname"');
// will produce 'http://example.com/?q=John'
window.open(`http://example.com/?q=${myname}`);

and likewise同样

// won't work
window.open('http://example.com/?q=(myname)');
// valid
window.open(`http://example.com/?q=${myname}`);

If you do need to support IE then window.open('http://example.com/?q=' + myname);如果您确实需要支持 IE,那么window.open('http://example.com/?q=' + myname); should work应该管用

Your string concatenation is not correct您的字符串连接不正确

var myname = "test"
window.open("http://example.com/?q=" + myname); // Classic string concatenation
window.open(`http://example.com/?q=${myname}`); // Using template literal 

You have to wrap the URL in Template Literals您必须将 URL 包装在模板文字

window.open(`http://example.com/?q=${myname}`);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM