javascript - 表单验证后如何重定向页面
问题描述
我是 JavaScript 新手,所以我所拥有的可能不是最好的方法,所以希望有人能纠正我!我有一个表单,它通过 ajax 调用发送数据来表达。
<Form name="FlightForm" id="FlightForm" action="/search" onSubmit={this.onSubmit} >
<div >
<label>FROM</label>
<input required type='text' name='originOne' id="originOne" onChange={this.setState.originOne} className="form-control" placeholder="Departing from"/>
</div>
<div>
Departure Date
<DatePicker className="form-control" required minDate={new Date()} name='date' selected={this.state.startDate} onChange={this.handleChange}/>
</div>
<p><button type="submit" name="search" id="search" value="true" onSubmit={this.loading()} className="w3-button w3-dark-grey">Search for destinations</button></p>
</Form>
export class Home extends React.Component {
constructor(props) {
super(props);
this.state = { originOne: '', originTwo: '', redirectToResult: false, startDate: new Date(), route:'', loader:false};
this.onSubmit= this.onSubmit.bind(this);
this.handleChange= this.handleChange.bind(this);
this.setMulti=this.setMulti.bind(this);
this.loading=this.loading.bind(this);
}
onChange = (e) => {
this.setState({
originOne: e.target.value, originTwo: e.target.value,
route:e.target.value});
};
setMulti = event => {
this.setState(
{route: event.target.value});
};
onSubmit = (e) => {
e.preventDefault();
const { originOne, originTwo , route} = this.state;
this.setState({ loading : true});
{this.loading()}
};
handleChange(date){
this.setState({
startDate:date
});
}
目前我有一个 ajax 调用将数据提交到 index.html 页面中引用的服务器。
$(document).ready(function(){
// click on button submit
$("#search").on('click', function(){
// send ajax
console.log($("#FlightForm").serialize()) ;
$.ajax({
url: '/', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#FlightForm").serialize(), // post data || get data
success : function(data, status, xhr ) {
window.location.replace("http://localhost:3000/searching");
},
error: function(xhr, resp, text) {
console.log("Error happening");
window.location.replace("http://localhost:3000/error");
}
})
});
});
我已将其构建为在提交后重定向到带有加载微调器的搜索页面,但这会覆盖表单验证的必填字段。
在表单验证后提交表单并重定向到下一页的最佳方法是什么?任何帮助将不胜感激谢谢!
解决方案
推荐阅读
- python - 在 Pandas 数据透视表的列中格式化时间格式
- r - 引用 dplyr 的 cross() 中的列名
- sql - 即使sql中的一个字段为空,如何显示两列字段的总和结果?
- apache - 删除 URL 中的 index.php 时出现重定向错误
- c# - 发布 .Net Framework Web API 时找不到 XML 文档?
- ssl - Netbeans - ftp连接上的过期证书
- javascript - 如何迭代评论集合以获得所有不同级别的评论回复?
- javascript - 将不同键的值放入单个数组
- flutter - 在按钮单击时使用未来构建器刷新主页上的数据 - 颤动
- mysql - 查询从两列获取比较结果