[英]How to add text input variable to URL in javascript
我现在遇到了最奇怪的问题。 我有这个JS代码:
function CreateChat() {
var chatName = document.getElementById("chatName").value;
window.location.href = "https://localhost:44321/CreateNewChat/CreateChat?ChatName=" + chatName;
}
事情是这样的,我无法让它工作。 它显然应该调用 controller 方法,但它不起作用。 If I hit that url with the project running and put anything at the end of it, like https://localhost:44321/CreateNewChat/CreateChat?ChatName=TestName , that test name variable will get to the controller without a problem. 如果我将“TestName”硬编码到代码中,而不是传递我之前定义的 chatName 变量,它将到达 controller,没问题。 Hell, if I debug the script, the chatName variable gets loaded correctly with my input, and if I console.log the url it will show up correctly (in fact, I can copy/paste that url and it will hit the controller method correctly )。 但是,正如上面提供的代码,它无论如何都不会命中 controller。 它将到达那个点,并切断执行,就好像 JS 代码中有错误一样。 你们对此有什么想法吗? 这让我发疯,真的。
以防万一,这就是我在 HTML 中定义文本输入的方式:
<input type="text" required class="form-control" id="chatName" aria-describedby="nameHelp" placeholder="Name your chat!">
编辑: chatName 上的 encodeURIComponent 也不起作用。
尝试将window.open
与_self
一起使用:
window.open ('https://localhost:44321/yadayada','_self',false);
您有一个提交按钮(我假设此按钮在form
内)...当您单击提交按钮时,表单被提交到表单的提交操作,这是提交操作的默认行为。
现在,如果您不想提交页面,可以将按钮类型更改为button
:
<button type="button" onclick="CreateChat()" class="btn btn-primary">Create a New Chat!</button>
或者,如果您确实需要submit
按钮,那么您需要阻止默认行为以更改window.location
:
function CreateChat(event) {
e.preventDefault(); // <-- don't submit the form
var chatName = document.getElementById("chatName").value;
window.location.href = "https://localhost:44321/CreateNewChat/CreateChat?ChatName=" + chatName;
}
您需要将event
传递给CreateChat
function:
<button type="submit" onclick="CreateChat(event)" class="btn btn-primary">Create a New Chat!</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.