首页 > 解决方案 > 使用 ajax 和面向对象的 php 最佳实践发送电子邮件

问题描述

我正在构建一个发送电子邮件的表单,我想使用面向对象的 Php 和 Ajax。

无论 Ajax 是什么,我都能够构建 PHP 后端(变量和函数),但是我在进行 Ajax 调用时遇到了问题,因为我还没有理解要遵循的步骤。

我的问题是我不太了解 ajax URL 的工作原理(对 PHP 文件的调用)。我应该尝试定位函数(以及我该怎么做)还是应该直接调用页面,在其中我将创建 json 函数以输出 json 文件以使用 ajax 解析?

这是我的代码:

页脚.php 和 main.js

$('#contact-form').on('submit',function(e) {
	e.preventDefault();
	$('.output-message').text('Loading...'); 

	const form = $(this);
	const post_url = $(this).attr("action"); 
	console.log(post_url);
	$.ajax({
		url: post_url,
		method: form.attr('method'),
		data: form.serialize(),
		type:'POST',
		success: function(result){
			console.log(result);
			if (result == 'success'){
				$('.output-message').text('Message Sent!');  
			} else {
				$('.output-message').text('Error Sending email!');
			}
		}
	});

	return false;   
});
<form id="contact-form" name="contact-form" action="Contact.php" method="POST" data-parsley-validate="">
	<div class="row">
		<div class="col-md-6">
			<div class="md-form mb-0">
				<input type="text" id="name" name="name" class="form-control" required="">
				<label for="name" class="">Your name</label>
			</div>
		</div>
		<div class="col-md-6">
			<div class="md-form mb-0">
				<input type="email" id="email" name="email" class="form-control" required="">
				<label for="email" class="">Your email</label>
			</div>
		</div>
	</div>
	<div class="row">
		<div class="col-md-12">
			<div class="md-form">
				<textarea type="text" id="message" name="message" rows="2" class="form-control md-textarea" required=""></textarea>
				<label for="message">Your message</label>
			</div>
		</div>
	</div>
	<div class="text-center text-md-right">
		<input type="submit" id="submit" class="btn-primary" name="submit" value="Request Info">
		<span class="output-message"></span>
	</div>
</form>

和 php 类:

联系方式.php

<?php
class Contact {

    public $name;
    public $email;
    public $message;
    public $admin = 'myemail@email.email';
    public $errors;

    public function sendMail() {

        $errors = "";

        if ($this->name == "") {
            $errors .= '- You forgot to enter a name!<br />';
        }

        if ($this->email == "") {
            $errors .= '- You forgot to enter an email!<br />';
        }

        if ($this->message == "") {
            $errors .= '- You forgot to enter a message!<br />';
        }

        if(empty($errors)) {
            $contents = "To: $this->name<br />Message: $this->message";
            $headers = "From:" . $this->email;
            $sendmail = mail($this->admin, $this->message, $contents, $headers);
        } else {
            echo '<p class=\'message error\'>';
            echo '<font color="black">' . $errors . '</font>';
            echo '</p><br />';
        }
    }
}

if(isset($_POST['submit'])) {
    $sendMail = new Contact();
    $sendMail->name = $_POST['name'];
    $sendMail->email = $_POST['email'];
    $sendMail->message = $_POST['message'];
    $sendMail->sendMail();
}

?>

javascript部分不起作用,我试图理解这部分:

const post_url = $(this).attr("action"); 

    $.ajax({
        url: post_url,

我应该在 PHP 中创建另一个函数来输出一个收集所有变量的 JSON 文件吗?

我的想法是我正在序列化 URL,然后我会将它发送到 PHP 文件,但我什至无法console.log()得到结果。

标签: phpajax

解决方案


稍微重构一下:

class Contact 
{
    public $name;
    public $email;
    public $message;
    public $admin = 'myemail@email.email';
    public $errors;

    public function sendMail() {

        $errors = "";

        if ($this->name == "") {
            $errors .= '- You forgot to enter a name!<br />';
        }

        if ($this->email == "") {
            $errors .= '- You forgot to enter an email!<br />';
        }

        if ($this->message == "") {
            $errors .= '- You forgot to enter a message!<br />';
        }

        if(empty($errors)) {
            $contents = "To: $this->name<br />Message: $this->message";
            $headers = "From:" . $this->email;
            $sendmail = mail($this->admin, $this->message, $contents, $headers);
        } else {
            throw new Exception($errors, 400);
        }
    }
}

if(isset($_POST['submit'])) {
    $sendMail = new Contact();
    $sendMail->name = $_POST['name'];
    $sendMail->email = $_POST['email'];
    $sendMail->message = $_POST['message'];
    header('Content-Type: aaplication/json');

    try {
        $sendMail->sendMail();
        echo json_encode(array('success' => 'success'));
    } catch (Exception $e) {
        header ('HTTP/1.1 400 Bad Request')
        $errors = array('error' => $e->getMessage);
        echo json_encode($errors);
    } 
}

我让它返回字符串而不是在类中回显,并且我在错误时引发了异常。此外,由于我们发送到 JS,所以我让它返回 JSON。

最后,在此处更改 JS:

$.ajax({
    url: post_url,
    method: form.attr('method'),
    data: form.serialize(),
    type:'POST',
    success: function(result){
        console.log(result);
        $('.output-message').text('Message Sent!');  
    }
    error: function(result) {
        console.log(result);
        $('.output-message').text('Error Sending email!');
    }
});

JS会检查一个200,所以知道它是否成功。由于您现在发送 400 错误,错误功能将触发!试试看:-)


推荐阅读