[英]Dynamic form action pointing to Express route
I've been trying to create a HTML form in my nodejs app, which directs to the appropriate express route when submitted. 我一直试图在我的nodejs应用程序中创建一个HTML表单,该表单在提交时会定向到适当的快递路线。 From this answer , I've gotten to the solution below:
从这个答案 ,我得到了下面的解决方案:
<script>
$('#controlPanel').submit(function(event) {
var view = document.getElementsByName('selectView').value;
var date = document.getElementsByName('selectDate')
.value
.toISOString()
.slice(0, 10);
var action = "/".concat(view).concat("/").concat(date);
$(this).attr('action', action);
});
</script>
However, the problem is, the resulting action string is wrong no matter what methods and functions I put the component elements through. 但是,问题是,无论我使用哪种构成要素的方法和函数,生成的动作字符串都是错误的。
Instead of something like " http://example.page/month/2018-01-01 " 而不是类似“ http://example.page/month/2018-01-01 ”
I get something like " http://example.page/?selectView=month&selectDate=2018-01-01 " 我得到类似“ http://example.page/?selectView=month&selectDate=2018-01-01 ”的内容
What could I do to ensure the dynamic action conforms to the former example? 我该怎么做才能确保动态动作符合前面的示例?
EDIT: The HTML used (also appended surrounding script html tags to code above): 编辑:所使用的HTML(也将周围的脚本html标签附加到上面的代码中):
<form id="#controlPanel">
View:<select name="selectView">
<option value="year">Year</option>
<option value="month">Month</option>
<option value="week">Week</option>
<option value="day">Day</option>
</select><br/>
Date: <input type="date" name="selectDate" min="2007-01-01"><br/>
<input type="submit" value="Submit">
</form>
Discovered a few things trying to solve this: 发现了一些尝试解决此问题的方法:
For unknown reasons, using attr() didn't work. 由于未知原因,使用attr()无效。
Trying to set the method to POST caused an exception (yes, even when I made the changes to the router to have the route use POST). 尝试将方法设置为POST会导致异常(是的,即使我对路由器进行了更改以使路由使用POST)。
Using GET still sticks GET parameters with a ? 使用GET仍然会使GET参数带有? separator at the end, but the route functions as intended despite this.
分隔符在最后,但是尽管如此,路由仍按预期运行。
The solution I ended up with, for others trying to do something similar: 对于其他尝试做类似事情的人,我最终得到了解决方案:
<script>
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("#controlPanel").addEventListener("submit", function(event) {
event.preventDefault();
var view = document.getElementsByName('selectView')[0].value;
var date = document.getElementsByName('selectDate')[0].value !== "" ? document.getElementsByName('selectDate')[0].value.slice(0, 10) : "";
var action = "/".concat(view).concat("/").concat(date);
document.getElementById("#controlPanel").action = action;
document.getElementById("#controlPanel").submit();
});
});
</script>
The only relevant bit of HTML: HTML的唯一相关位:
<form id="#controlPanel" method="get" action="">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.