将AJAX成功/错误消息添加到Formcarry

时间:2019-07-08 14:25:07

标签: javascript jquery reactjs

我是React的新手,我正在开发我的第一个网站。我需要制作一个联系表,由于我很难从头开始制作它,所以我使用了Formcarry并将其与我的React App连接起来。现在,我需要使AJAX成功和出现错误消息,但是我并没有那么幸运。

反应:

import React from "react";
import axios from "axios";


class Form extends React.Component {
  constructor(props){
    super(props);
    this.state = {name: "", surname: "", email: "", message: ""};
  }

  handleForm = e => {
    axios.post(
      "https://formcarry.com/s/LxMYb0c7kXC", 
      this.state, 
      {headers: {"Accept": "application/json"}}
      )
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

    e.preventDefault();
  }

  handleFields = e => this.setState({ [e.target.name]: e.target.value });

  render() {
    return (
      <form id="ajaxForm" onSubmit={this.handleForm}>
        <label htmlFor="name">Name</label>
        <input type="text" id="name" name="name" onChange={this.handleFields} />

        <label htmlFor="surname">Surname</label>
        <input type="text" id="surname" name="surname" onChange={this.handleFields} />

        <label htmlFor="email">Email</label>
        <input type="email" id="email" name="email" onChange={this.handleFields} />

        <label htmlFor="message">Your Message</label>
        <textarea name="message" id="message" onChange={this.handleFields}></textarea>

        <button type="submit">Send</button>
      </form>
    );
  }
}

export default Form;

然后我尝试将jQuery添加到公用文件夹中的index.html:

   $("#ajaxForm").submit(function(e){
        e.preventDefault();
        var href = $(this).attr("action");
        $.ajax({
            type: "POST",
            dataType: "json",
            url: href,
            data: $(this).serialize(),
            success: function(response){
                if(response.status == "success"){
                    alert("We received your submission, thank you!");
                }else{
                    alert("An error occured: " + response.message);
                }
            }
        });
    });
});

添加jQuery后,未显示成功和错误消息,我做错了吗?

星期二,正在发送电子邮件,该部分正常工作。

我在heroku上建立了我的网站:

https://trustmypetsitter.herokuapp.com/contactpage

1 个答案:

答案 0 :(得分:0)

axios不返回带有response的响应,您需要使用此

console.log(response.data);

因此,为了正确处理成功和错误消息,请使用以下命令:

handleForm = e => {
    axios.post(
      "https://formcarry.com/s/LxMYb0c7kXC", 
      this.state, 
      {headers: {"Accept": "application/json"}}
      )
      .then(function (response) {
        const { data } = response;

        if(data.status == "success"){
            // handle success
        }
        else{
            // handle formcarry error
            console.log(data.message)
        }
      })
      .catch(function (error) {
        // handle network error
        console.log(error);
      });

    e.preventDefault();
  }

希望有帮助!