React在输入onChange内发送AJAX请求

时间:2018-03-19 12:02:16

标签: ajax reactjs

这是我的 SearchForm.js ,关于更改输入keywords我需要在其他服务器上发送带有此输入值的AJAX请求,获取一些值并使用它们自动完成此操作输入。有可能吗?如何制作?

import React from 'react';
import ReactDOM from 'react-dom';

class SearchForm extends React.Component {
    constructor(props) {
      super(props)

      this.state = {
       keywords: '',
       city: '',
       date: ''     
      }

      //this.handleChange = this.handleChange.bind(this)
      //this.handleSubmit = this.handleSubmit.bind(this)

      this.handleKeywordsChange = this.handleKeywordsChange.bind(this);
      this.handleCityChange = this.handleCityChange.bind(this);  
     }

    handleKeywordsChange(e) {      
        this.setState({
          keywords: e.target.value
        });
    }

    handleCityChange(e) {      
        this.setState({
          city: e.target.value
        });
    }

    render() {
        return ( 
            <form className='form search-form' onSubmit={this.handleSubmit}>
                <div className="form-row">
                  <div className="form-group col-md-5">
                    <label htmlFor="keywords">Keywords</label>
                    <input type="text" className="form-control" name="keywords" id="keywords" placeholder="Keywords" onChange={this.handleKeywordsChange} value={this.state.keywords} />

                  </div>

                  <div className="form-group col-md-5">
                    <label htmlFor="city">City</label>
                    <input type="text" className="form-control" name="city" id="city" placeholder="City" onChange={this.handleCityChange} value={this.state.city} />
                  </div>

                  <div className="form-group col-md-2">
                    <label htmlFor="date">Date</label>
                    <select className="form-control" name="date" id="date" onChange={this.handleChange} value={this.state.date}>
                      <option>1</option>
                      <option>2</option>
                      <option>3</option>
                      <option>4</option>
                      <option>5</option>
                    </select>
                  </div>
                 </div>

                 <div className="form-row">
                     <div className="form-group col-md-12">
                        <input id='formButton' className='btn btn-primary' type='submit' placeholder='Send' />
                    </div>
                 </div>
            </form>
        )
    }
}

export { SearchForm }

1 个答案:

答案 0 :(得分:2)

使用axios api来调用api并获取数据

onKeyUp(e) {
  axios.get('/seachdata?keywords='+e.target.value)
  .then(function (response) {
     this.setState({autosearchresponse: response.data})
  })
  .catch(function (error) {
    console.log(error);
  });
}

在this.state.autosearchresponse中搜索数据集 你可以使用autosearch响应作为html

 {this.state.autosearchresponse.map((value, i)=>
  <div key={i}>{value}</div>    
)}

将onKeyUp函数绑定到输入