首页 > 解决方案 > 表单验证后如何重定向页面

问题描述

我是 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");
                }
            })
        });
    });

我已将其构建为在提交后重定向到带有加载微调器的搜索页面,但这会覆盖表单验证的必填字段。

在表单验证后提交表单并重定向到下一页的最佳方法是什么?任何帮助将不胜感激谢谢!

标签: javascriptreactjsexpress

解决方案


推荐阅读