React选择框从json文件获取数据

时间:2016-12-24 06:20:25

标签: javascript ajax reactjs post get

我使用选择框做出反应。 我想从json文件(服务器GET)获取数据并将此数据设置为选择框。选择并提交后将其发布到服务器。 我已经尝试使用ajax将输入数据发布到服务器,但我不知道如何获取选择框的数据并将其发布到服务器

这是输入代码:

var CitiesContent=React.createClass({
    componentDidMount() {
    this.props.form.setFieldsValue({
      eat: true,
      sleep: true,
      beat: true,
    });

  },

  getInitialState : function(){
    return {}
  },

  submit:function(e){
    e.preventDefault();
     var data ={
      name:this.state.name
    }
    this.props.form.validateFieldsAndScroll((errors, values) => {
      if (errors) {
        console.log('Errors in form!!!');
        return;
      }
      else{
           $.ajax({
                type: 'POST',
                url: 'https://google.com',
                data: data
        })
      }
    });
  },

  nameChange(e){
    this.setState({email: e.target.value})
  },

  render:function(){
    const { getFieldDecorator } = this.props.form;
    return(
        <div className="mainTotal container-fluid">
            <div className="mainTotalChild">
                <Form onSubmit={this.submit} >
                    <FormItem id="select1" label="Name" >
                        {getFieldDecorator('select1', {
                            rules: [
                            { required: true, message: 'Field Is required' },
                            ],
                        })(
                        <Input id="control-input1" placeholder="Name"  style={{ width: "85%"}}/>
                        )}
                    </FormItem>
                    <FormItem wrapperCol={{ span: 24, offset: 0 }} >
                        <Button className="buttonTo" type="submit" onClick={this.submit}>Submit</Button>
                    </FormItem>
                </Form>
            </div>
        </div>
    );
  }
})

2 个答案:

答案 0 :(得分:1)

您可以为state维护select box

做这样的事

var FormComponent = React.createClass({
 //all are `React` component methods
  getInitialState: function(){
    return {
      selectedValue: null,
      selectOptions : []
    }
  },
  componentWillMount = function(){
    //make AJAX call and store response in state
    $.ajax("YOUR API", function(response){
      this.setState({
        selectOptions : response || [],
        selectedValue : response[0] //taking first value as selected value
      });
    })
  },
  componentDidMount = function(){
    //do anything you want after mount
  },
  handleSelect = function(e){
    this.setState({
      selectedValue : e.target.value
    });
  },
  handleSubmit = function(e){
    e.preventDefault();
    //submit form using AJAX POST
    //select value in this.state.selectedValue
    //$.ajax()
  },
  render = function(){
    return(
      <form onSubmit={this.handleSubmit}>
      <select value={this.state.selectedValue} onChange={this.handleSelect}>
        {
          this.state.selectOptions.map(function(item){
            return(
              <option value={item}>{item}</option>
            )
          })
        }
      </select>
      </form>
    )
  }

});

答案 1 :(得分:0)

这是我所说的代码:

var CitiesContent=React.createClass({
  getInitialState : function(){
    return {
      selectedValue: null,
      selectOptions : []
    }
  },

  componentWillMount(){
    $.ajax("url", function(response){
      this.setState({
        selectOptions : response || [],
        selectedValue : response[0] //taking first value as selected value
      });
    })
  },

  handleSelect :function(e){
    this.setState({
      selectedValue : e.target.value
    });
  },

    componentDidMount() {
      this.props.form.setFieldsValue({
        eat: true,
        sleep: true,
        beat: true,
      });

  },



  submit:function(e){
    e.preventDefault();
     var data ={
      name:this.state.name
    }
    this.props.form.validateFieldsAndScroll((errors, values) => {
      if (errors) {
        console.log('Errors in form!!!');
        return;
      }
      else{
           $.ajax({
                type: 'POST',
                url: 'https://google.com',
                data: data,
                contentType:'application/json',
                dataType:'json',
                success:function(result){console.log("success")},
                error:function(result){console.log("error!")}
        })
      }
    });
  },

  nameChange(e){
    this.setState({email: e.target.value})
  },

  render:function(){
    const { getFieldDecorator } = this.props.form;
    return(
        <div className="mainTotal container-fluid">
            <div className="mainTotalChild">
                <Form onSubmit={this.submit} >
                    <FormItem id="select1" label="Name" >
                        {getFieldDecorator('select1', {
                            rules: [
                            { required: true, message: 'Field Is required' },
                            ],
                        })(
                        <Input id="control-input1" placeholder="Name"  style={{ width: "85%"}}/>
                        )}
                    </FormItem>
                    <FormItem id="select2" label="Route" labelCol={{ span: 24}} wrapperCol={{ span: 24 }} >
                        {getFieldDecorator('select2', {
                            rules: [
                            { required: true, message: 'Field Is required' },
                            ],
                        })(
                            <Select value={this.state.selectedValue} onChange={this.handleSelect}>
                                {
                                  this.state.selectOptions.map(function(item){
                                    return(
                                      <Option value={item}>{item}</Option>
                                    )
                                  })
                                }
                              </Select>
                        )}
                    </FormItem>
                    <FormItem wrapperCol={{ span: 24, offset: 0 }} >
                        <Button className="buttonTo" type="submit" onClick={this.submit}>Submit</Button>
                    </FormItem>
                </Form>
            </div>
        </div>
    );
  }
})