栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Ajax在React.js中提交表单

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Ajax在React.js中提交表单

我找到了解决方案。这是我的联系人组件:

import React, { Component } from 'react';// Contact component render contact formclass Contact extends React.Component {  constructor(props){    super(props);    this.state = {      contactEmail: '',      contactMessage: ''    };    this._handleSubmit = this._handleSubmit.bind(this);    this._handleChange = this._handleChange.bind(this);    this._handleChangeMsg = this._handleChangeMsg.bind(this);  }  // Change state of input field so text is updated while typing  _handleChange(e) {    this.setState({      contactEmail: e.target.value,    });  }  // Change state of input field so text is updated while typing  _handleChangeMsg(e) {    this.setState({      contactMessage: e.target.value    });  }  _handleSubmit(e) {    e.preventDefault();    this.setState({      contactEmail: '',      contactMessage: ''    });    $.ajax({      url: process.env.NODE_ENV !== "production" ? '/getMail' : "http://www.fransbernhard.se/magden/php/mailer.php",      type: 'POST',      data: {        'form_email': this.state.contactEmail,        'form_msg': this.state.contactMessage      },      cache: false,      success: function(data) {        // Success..        this.setState({          contactEmail: 'success',          contactMessage: '<h1>Kontakt skickad!</h1><p>Återkommer så fort som möjligt.</p>'        });        $('#formContact').slideUp();        $('#formContact').after(this.state.contactMessage);        console.log('success', data);      }.bind(this),      // Fail..      error: function(xhr, status, err) {        console.log(xhr, status);        console.log(err);        this.setState({          contactEmail: 'danger',          contactMessage: '<h1>Sorry det blev fel</h1><p>Försök gärna igen, eller mejla mig direkt på magdamargaretha@gmail.com</p>'        });        console.log(this.state.contactEmail + this.state.contactMessage + 'fail');      }.bind(this)    });  }  render() {    return (      <div className="contact" id="contact">        <div className="filter">          <form className="form" onSubmit={this._handleSubmit} id="formContact"> <label>Email</label> <input id="formEmail" type="email" name="formEmail" value={this.state.contactEmail} onChange={this._handleChange} required/> <label>Meddelande</label> <textarea id="formMsg" name="formMsg" rows="8" cols="40" value={this.state.contactMessage} onChange={this._handleChangeMsg} required></textarea> <input type="submit" value="Submit" className="btn--cta" id="btn-submit" />          </form>        </div>      </div>    )  }}export default Contact;

mailer.php文件:

<?php  // trim() function strips any white space from beginning and end of the string  $email = filter_var(trim($_POST["form_email"]), FILTER_SANITIZE_EMAIL);  //  strip_tags() function strips all HTML and PHP tags from a variable.  $message = strip_tags($_POST["form_msg"]);  // Check that data was sent to the mailer.  if ( empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {    // Set a 400 (bad request) response pre and exit.    http_response_pre(400);    echo "Oops! There was a problem with your submission. Please complete the form and try again.";    exit;  }  // Set the recipient email address.  $recipient = "mimilundberg@icloud.com";  // Set the email subject.  $subject = "Message to magdalundberg.se from: $email";  // Build the email content.  $body .= "Email: $emailnn";  $body .= "Message: n$messagen";  // success  $success = mail($recipient, $subject, $body, "From:" . $email);  // Send the email.  if ($success) {    // Set a 200 (okay) response pre.    http_response_pre(200);    echo "Thank You! Your message has been sent.";  } else {    // Set a 500 (internal server error) response pre.    http_response_pre(500);    echo "Oops! Something went wrong and we couldn’t send your message.";  }?>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/616525.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号