Как я могу опубликовать данные о реакции и ajax на сервере rails?

2

Я разрабатываю приложение с реакциями на интерфейсе и рельсах на бэкэнде. Я новичок в рельсах. Я разработал систему регистрации с помощью reactjs, и теперь я хочу опубликовать данные на сервере. Для этого я не использую драгоценные камни с рельсами. Я не знаю, что делать дальше для отправки данных на сервер. Может кто-нибудь, пожалуйста, просветит меня? Что мне теперь делать? Есть ли что-то, что я должен предоставить? PS Я не использую драгоценный камень с реактивной решеткой.

Мой Код Реагирования для регистрации комнаты (сокращенный путем удаления описания и некоторых других полей)

var fieldValues = {
  ownerName:'',
  email:'',
  phoneNumber:'',
  image:[]

}


class AddRent extends React.Component{
 constructor(props,context) {
        super(props,context);
        this.state = {
            step: 1
        };
    }

  saveValues(field_value) {
    return function() {
      fieldValues = Object.assign({}, fieldValues, field_value)
    }()
    console.log('fieldValues are', fieldValues);
  }


  nextStep(step) {
    var step = this.state.step;
    var newStep = step+1;
    this.setState({step:newStep});
  }

  previousStep(step) {
    var step = this.state.step;
    var newStep = step-1
    this.setState({
      step : newStep
    });
  }


  showStep() {
  switch (this.state.step) {
    case 1:
      return <RenderPersonalInfo fieldValues={fieldValues}
                            nextStep={this.nextStep.bind(this)}
                            previousStep={this.previousStep.bind(this)}
                            saveValues={this.saveValues.bind(this)} />
    case 6:
      return <RenderPhotos fieldValues={fieldValues}
                           nextStep={this.nextStep.bind(this)}
                           previousStep={this.previousStep.bind(this)} />
  }
}

  render() {
    var style = {
      width : (this.state.step / 6 * 100) + '%'
    }

    return (
      <main>
        <span className="progress-step">Step {this.state.step}</span>
        <progress className="progress" style={style}></progress>
        {this.showStep()}
      </main>
    )
  }
};

class RenderPersonalInfo extends React.Component{
  render(){
    return(
            <div>
              <h3>Personal Information</h3>
              <p className="subtitle">Provide your authentic information so rent seekers can contact you</p>
              <hr/>
              <div className="col-md-4">
                <label htmlFor='name'>Owner Name</label>
                <input ref="name" defaultValue={this.props.fieldValues.ownerName} type="textbox" className="form-control" id="name" placeholder="Owner name" />
              </div>
              <div className="col-md-4">
                <label htmlFor="email">Email</label>
                <input ref="email" defaultValue={this.props.fieldValues.email} type="email" className="form-control" id="email" placeholder="email" />
              </div>
              <div className="col-md-4">
                <label htmlFor="phoneNumber">Phone Number</label>
                <input ref="phone" defaultValue={this.props.fieldValues.phoneNumber} type="textbox" className="form-control" id="phoneNumber" placeholder="phone number" />
              </div>
              <hr/>
                <div className="row continueBtn text-right">
                    <button className="btn how-it-works" ref="personalInfo" onClick={this.nextStep.bind(this)}>Continue</button>
                </div>
            </div>
      );
  }
  nextStep(step){
     var data = {
          ownerName  : this.refs.name.value,
          email : this.refs.email.value,
          phoneNumber: this.refs.phone.value,
        }
        console.log(data.ownerName);
        if ((data.ownerName)&&(data.email)&&(data.phoneNumber)) {
          this.props.saveValues(data);
          this.props.nextStep();
        }
        else{
          alert('please enter the name, email and phone number');
        }
  }
};

 class RenderPhotos extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            files: []
        };
    }

    onDrop(files) {
      console.log('Received files: ', files);
      this.setState({
          files: files
      });

      var image = [];
      image = new FormData(files);
      $.each(files,function(i,file){
        image.append('image',file);
      });
     $.ajax({
      url:"",
      data:image,
      contentType:false,
      processData:false,
      type:'POST',
      mimeType: "multipart/form-data",
      success: function(data) {
        console.log('success');
      }
     });
  }

    showFiles() {
        const { files } = this.state;
        console.log('files',files);

        if (!files.length) {
            return null;
        }

        return (
            <div>
                <h3>Dropped files: </h3>
                <ul className="gallery">
                    {
                        files.map((file, idx) => {
                            return (
                                <li className="col-md-3" key={idx}>
                                    <img src={file.preview} width={200}/>
                                    <div>{file.name}</div>
                                </li>
                            )
                        })
                    }
                </ul>
            </div>
        );
    }

    render() {
      return (
           <div>
                <p>Add photos of spaces to give more insight of your space </p>
                <hr/>
                <div className="col-md-12">
                <form method="POST" encType="multipart/form-data">
                  <Dropzone onDrop={this.onDrop.bind(this)}>
                    Try dropping some files here, or click to select files to upload.
                </Dropzone>
              </form>
                {this.showFiles()}
              </div>
              <div className="row continueBtn text-right">
                    <button className="btn how-it-works pull-left" onClick={this.props.previousStep.bind(this)}>Back</button>
                    <button className="btn how-it-works" onClick={this.nextStep.bind(this)}>Submit</button>
               </div>
            </div>

      );
    }

       nextStep(step){
                  var sendData={'ownerName':this.props.fieldValues.ownerName,
                        'email':this.props.fieldValues.email,
                        'phoneNumber':this.props.fieldValues.phoneNumber,
                      }
                  console.log(sendData.email);
                  $.ajax({
                  url:"",
                  data:sendData,
                  type:'POST',
                  success: function(data) {
                    console.log('success');
                  }
                 });
       }


}

export default AddRent;

Мой кабинет

class RoomsController < ApplicationController
    def index
        @rooms = Room.all
    end

    def new
      @room = Room.new
    end

    def create
      @room = Room.new(listing_params)
      respond_to do |format|
        if @room.save
          format.html { redirect_to @room, notice: 'Room was successfully listed.' }
          format.json { render json: @room }
      else
        format.html {render :new}
        format.html {render json:@room.errors}
      end
    end

    private

    def listing_params
      params.require(:room).permit(:ownerName, :email, :phoneNumber, :listingName, :summary, :property, :room, :price, :city, :place, :water, :amenities, :is_published)
    end
end

Модели для комнаты (файл миграции)

class CreateRooms < ActiveRecord::Migration
  def change
    create_table :rooms do |t|
      t.string :ownerName
      t.string :email
      t.integer :phoneNumber
      t.string :listingName
      t.text :summary
      t.string :property
      t.integer :room
      t.integer :price
      t.string :city
      t.string :place
      t.string :water
      t.string :amenities
      t.boolean :is_published

      t.timestamps null: false
    end
  end
end
  • 1
    Где именно проблема? Включены вызовы ajax, что кажется разумным (хотя URL-адреса пусты?). Не зная, какие ошибки вы получаете, или на какой стадии вы застряли, трудно понять.
  • 0
    Я понятия не имею . я думаю, что я должен передать URL, который отображает, чтобы создать действие в контроллере и создать create.js.erb, но я не уверен. Это то, что я должен сделать? Я хочу этой идеи, потому что я не видел ничего такого в Интернете, кроме как через реактивный рельс. Я хочу знать, что мне делать дальше после создания формы, полностью основанной на реагировании.
Показать ещё 2 комментария
Теги:
ruby-on-rails-3

1 ответ

0

Вам нужно сохранить токен csrf в заголовках ajax или вам нужно отключить защиту csrf

Ещё вопросы

Сообщество Overcoder
Наверх
Меню