我正在尝试使用Json和AJAX发送带有数据数组的php表单邮件程序,但出于某种原因,邮件是在没有数据的情况下发送的... (我测试了jason字符串并验证它以确保它包含数据)
这是我的代码:
JSON:
function submitFields() {
form_elements = [];
$('.dataField').each(function () {
frm_name = $(this).attr('name');
frm_qty = $(this).val();
frm_price = $(this).data('price');
current_frm_obj = {name:frm_name, qty:frm_qty, price:frm_price};
form_elements.push(current_frm_obj);
});
$.ajax({
type: "POST",
url: "mailer.php",
data: { result:JSON.stringify(form_elements) },
success : function(response) {
console.log(form_elements);
alert(response);
}
});
}
PHP邮件程序:
$data = $_POST["result"];
$decoded = json_decode($data);
$errors = '';
$myemail = 'office@studiodeshe.com';
$to = $myemail;
$email_subject = "Form info";
$email_body =
$decoded = json_decode($data);
foreach ($decoded as $curr_element) {
$fieldName = $curr_element->name;
$fieldQty = $curr_element->qty;
$fieldPrice = $curr_element->price;
if ( $fieldQty != 0 ) {
$fieldName .': <br />' . $fieldQty;
if ($fieldPrice != 0) {
'Qty: ' . $fieldQty . '<br />';
'Price: ' . $fieldPrice . '<br />';
'Total: ' . ($fieldPrice*$fieldQty) . '<br /><br />';
}
}
}
$headers = "From: studiodeshe <office@studiodeshe.com> \n";
$headers .= 'Content-type: text/html; charset=utf-8';
mail($to,$email_subject,$email_body,$headers);
header('Location: ty.html');
我猜我在尝试解码邮件中的数据时遇到了一些问题,但无法找到解决方案......
答案 0 :(得分:0)
好的,我解决了。如果将来有人需要解决方案,那就是:
来自json的数据应该在开头解析,并保存到var中,如下所示:
$data = $_POST["result"];
$decoded = json_decode($data);
$mailData = "";
foreach ($decoded as $curr_element) {
$fieldName = $curr_element->name;
$fieldQty = $curr_element->qty;
$fieldPrice = $curr_element->price;
if ( $fieldQty != 0 ) {
if ($fieldPrice != 0) {
$input = $fieldName .': <br />
Qty: ' .$fieldQty. '<br />
Price: ' . $fieldPrice . '<br />
Total: ' . ($fieldPrice*$fieldQty) .
'<br /><br />';
$mailData .= $input;
}
}
}
$errors = '';
$myemail = 'studio@studiodeshe.com';//<-----Put Your email address here.
$to = $myemail;
$email_subject = "Configurator Lead";
$email_body = $mailData;
$headers = "From: studiodeshe <office@studiodeshe.com> \n";
$headers .= 'Content-type: text/html; charset=utf-8';
mail($to,$email_subject,$email_body,$headers);