我试图用3个输入(名称,电子邮件,文本)创建SweetAlert表单。提交后,此表单必须将表单数据发送到管理员电子邮件。我做到了,一切正常!但是我确定我的控制器代码无效。
CMS:OpenCart 2.3 + SweetAlert 2。
这是SweetAlert表单+ Ajax请求:
<script type="text/javascript">
window.onload = function () {
var a = document.getElementById('director');
a.onclick = function() {
Swal({
type: 'warning',
title: 'Your message',
html:
'<input name="name" id="swal-input1" class="swal2-input" placeholder="Your name">' +
'<input name="email" id="swal-input2" class="swal2-input" placeholder="Email">' +
'<textarea name="text" id="swal-textarea1" class="swal2-textarea" placeholder="Enter your text..." style="display: flex;"></textarea>',
showCancelButton: true,
confirmButtonColor: '#ff5908',
cancelButtonColor: '#666',
confirmButtonText: 'Send',
cancelButtonText: 'Cancel',
preConfirm: function () {
return new Promise(function (resolve) {
resolve([
$('#swal-input1').val(),
$('#swal-input2').val(),
$('#swal-textarea1').val()
])
})
},
}).then(function (result) {
if (result.value) {
var result = {};
result.name = $('#swal-input1').val();
result.email = $('#swal-input2').val();
result.text = $('#swal-textarea1').val();
var data = JSON.stringify(result);
$.ajax({
url:"index.php?route=common/message/index",
type: "post",
data: data,
dataType: "json",
success: function() {Swal({type: 'success', text: 'Message sent'});},
error: function(xhr,status,error){
console.log(status);
console.log(error);
}
})
}
})
return false;
}
}
</script>
之后,ajax请求将发送到“ Message”控制器的“ index”方法。
<?php
class ControllerCommonMessage extends Controller {
public function index() {
$request_body = file_get_contents('php://input');
$data = json_decode($request_body);
$username = $data->name;
$email = $data->email;
$msg = $data->text;
$subject = 'Test email from: '.$email;
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo('mail@mail.com');
$mail->setFrom($this->config->get('config_email'));
$mail->setSender(html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'));
$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
$mail->setHtml($msg);
$mail->send();
}
}
因此,该表单正在运行,消息发送成功。但是,我不喜欢这段代码:
$request_body = file_get_contents('php://input');
$data = json_decode($request_body);
我也试图这样写:
if (isset($this->request->post['data'])) {
$result = $this->request->post['data'];
var_dump($result);
} else {
echo 'empty';
}
但是没有任何效果。 “结果”为空。我在做什么错了?