如何在ReactJS中从表单构造POST的数据?

时间:2016-02-07 20:28:36

标签: jquery python ajax django reactjs

我有一个基本的React组件,用于向API端点发出POST(使用Django REST Framework)的联系表单。该端点处理实际发送,等等。

我正在使用jQuery来处理Ajax业务 - 我知道这太过分了;它将在以后删除 - 但我似乎无法理解如何从我的组件中的表单构造值以提交到我的端点。

这是我的组件:

var ContactForm = React.createClass({
  getInitialState: function() {
    return {
      name: '',
      email: '',
      message: '',
      url: '',
    };
  },
  handleNameChange: function (e) {
    this.setState({name: e.target.value})
  },
  handleEmailChange: function (e) {
    this.setState({email: e.target.value})
  },
  handleMessageChange: function (e) {
    this.setState({message: e.target.value})
  },
  handleURLChange: function (e) {
    this.setState({url: e.target.value})
  },
  handleFormSubmit: function (e) {
    e.preventDefault();
    var name = this.state.name.trim();
    var email = this.state.email.trim();
    var message = this.state.message.trim();
    var url = this.state.url.trim();
    if (url) {
      return;
    };
    if (!name || !email || !message) {
      return;
    };
    var formData = {
      name: name,
      email: email,
      message: message
    };
    this.props.onContactFormSubmit({formData});
    this.setState({
      name: '',
      email: '',
      message: '',
      url: ''
    });
  },
  render: function () {
    return (
      <form onSubmit={this.handleFormSubmit} method="POST">
        <div>
          <label for="id_name">Name:</label>
          <input onChange={this.handleNameChange} id="id_name" maxlength="200" name="name" type="text" />
        </div>
        <div>
          <label for="id_email">Email:</label>
          <input onChange={this.handleEmailChange} id="id_email" maxlength="254" name="email" type="email" />
        </div>
        <div>
          <label for="id_message">Message:</label>
          <textarea onChange={this.handleMessageChange} cols="40" id="id_message" name="message" rows="10" />
          <span className="helptext">Note: Plain text only. All HTML will be stripped and content escaped on submission.</span>
        </div>
        <div className="honeypot">
          <label for="id_url">Url:</label>
          <input onChange={this.handleURLChange} id="id_url" name="url" type="text" />
        </div>
        <button type="submit" className="btn btn-default">Send</button>
      </form>
    );
  }
});
var ContactFormContainer = React.createClass({
  getInitialState: function() {
    return {data: []};
  },
  onContactFormSubmit: function (formData) {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: formData,
      success: function(data) {
        console.log('Posted correctly', data)
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  render: function () {
    return (
      <ContactForm onContactFormSubmit={this.onContactFormSubmit} />
    );
  }
});
var communicationCreateUrl = $('#contact_form_container').data('url');
ReactDOM.render(
    <ContactFormContainer url={communicationCreateUrl} />,
    document.getElementById('contact_form_container')
);

这导致了Django方面的一个字典:

{'formData[name]': 'Patrick', 'formData[email]': 'patrick@gmail.com', 'formData[message]': 'This is a test.'}

我需要的是这样的东西,这是使用此请求进行POST的结果(message=Some+test&name=Patrick+Beeson&email=patrickbeeson%40gmail.com),类似于在jQuery中调用serialize()

{'name': 'Patrick', 'message': 'This is a test', 'email': 'patrick@gmail.com'}

我应该做些什么?

1 个答案:

答案 0 :(得分:0)

您可以使用Ajax Post将JSON发送到Django,然后将参数作为dict()处理。这是一个例子:

在浏览器(JQuery / JavaScript)中:

    function newModule() {

        var my_data = $("#my_element").val(); // Whatever value you want to be sent.

        $.ajax({
            url: "{% url 'modules' %}",       // Handler as defined in Django URLs. 
            type: "POST",                     // Method.
            dataType: "json",                 // Format as JSON (Default).
            data: {
                path: my_data,                // Dictionary key (JSON). 
                csrfmiddlewaretoken: 
                         '{{ csrf_token }}'   // Unique key.
            },

            success: function (json) {

                // On success do this.

            },

            error: function (xhr, errmsg, err) {

                // On failure do this. 

            }

        });

在服务器引擎(Python)中:

def handle(request):

    # Post request containing the key.  
    if request.method == 'POST' and 'my_data' in request.POST.keys():

        # Retrieving the value.
        my_data = request.POST['my_data']

    # ...