我在reactjs中创建了一个登陆页面,该页面上是一个contactform,我试图用php发送电子邮件,但它不起作用。我知道您不能在反应中使用php,但我在网上阅读到您可以这样做。我认为与contactform.php的链接可能有问题。它确实显示404错误消息,我可以在控制台中看到它将所有信息置于状态。但是,当我单击提交时,什么也没发生。谁能解释我为什么?
constructor()
{
super();
this.state = {
organisatie: '',
naam: '',
email: '',
telefoon: '',
vraag: '',
error: null,
mailSent: false
};
}
handleFormSubmit = e => {
console.log(this.state);
e.preventDefault();
axios({
method: 'post',
url: `${API_PATH}`,
headers: { 'content-type': 'application/json' },
data: this.state
})
.then(result => {
this.setState({
mailSent: result.data.sent
})
})
.catch(error => this.setState({ error: error.message }));
};
并以html格式:
<div className="col-md-6 contactform pl-2">
<form action="/contactForm.php">
<p>Naam Organisatie / praktijk * </p>
<input type="text" id="praktijk" name="organisatie" required="" value={organisatie} onChange={e => this.setState({ organisatie: e.target.value })}/>
<p> Uw naam * </p>
<input type="text" id="name" name="naam" required="" value={naam} onChange={e => this.setState({ naam: e.target.value })}/>
<p>Uw e-mailadres * </p>
<input type="text" id="email" name="email" required="" value={email} onChange={e => this.setState({ email: e.target.value })} />
<p>Uw telefoonnummer * </p>
<input type="text" id="telnr" name="telefoon" required="" value={telefoon} onChange={e => this.setState({ telefoon: e.target.value })}/>
<p>Vraag / opmerking *</p>
<textarea id="bericht" name="vraag" required="" value={vraag} onChange={e => this.setState({ vraag: e.target.value })}> </textarea> <br />
<p><input type="checkbox" name="akkoord" value="akkoord" />Ik ga akkoord met de <a href="/algemene-voorwaarden">Algemene voorwaarden</a></p><br />
<input type="submit" className="btn-submit mt-3" onClick={e => this.handleFormSubmit(e)}/>
<div>
{this.state.mailSent &&
<div>Bedankt voor het invullen van het contactformulier! Er wordt zo snel mogelijk contact met u opgenomen.</div>
}
</div>
</form>
</div>
这就是我在php文件中所拥有的:
<?php
header("Access-Control-Allow-Origin: *");
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);
if (empty($_POST['naam']) && empty($_POST['email'])) die();
if ($_POST)
{
// set response code - 200 OK
http_response_code(200);
$subject = $_POST['naam'];
$to = "knevel.adinda@gmail.com";
$from = $_POST['email'];
// data
$msg = $_POST['telefoon'] . $_POST['vraag'];
// Headers
$headers = "MIME-Version: 1.0\r\n";
$headers.= "Content-type: text/html; charset=UTF-8\r\n";
$headers.= "From: <" . $from . ">";
mail($to, $subject, $msg, $headers);
// echo json_encode( $_POST );
echojson_encode(array(
"sent" => true
));
}
else
{
// tell the user about error
echojson_encode(["sent" => false, "message" => "Something went wrong"]);
}
?>