[英]Sending mail data from JS to PHP to be mail()'d
I'm having trouble with seemingly simple problem. 我在看似简单的问题上遇到了麻烦。
Using JQuery i want to POST an array containing 2 items, an email address and email content, to a simple PHP script that mails the customer's concern back to my own server email. 我想使用JQuery将一个包含2个项目(电子邮件地址和电子邮件内容)的数组发布到一个简单的PHP脚本中,该脚本将客户的关注点发送回我自己的服务器电子邮件中。
I am receiving the email, but it is blank because either im not encoding or decoding the JSON object correctly or something else. 我正在接收电子邮件,但它为空,因为我无法正确编码或解码JSON对象或其他内容。
Javascript: Javascript:
...
var JSONEmailRequest = new Object();
JSONEmailRequest.emailaddress = $("#emailInput").val();
JSONEmailRequest.content = $("#contentInput").val();
$.post("/email.php", JSON.stringify(JSONEmailRequest), function (data) {
//do stuff
});
...
PHP: PHP:
<?php
$POSTJSONObj = json_decode($POST['JSONEmailRequest']);
$email_to = "shawnandrews@saportfolio.ca";
$email_subject = "User enquiry from ".$POSTJSONObj['emailaddress'];
$email_body = $POSTJSONOb j['content'];
$result = mail($email_to,$email_subject,$email_body,"From: ".$email_to);
if(!$result) {
echo false;
} else {
echo true;
}
?>
Don't convert the JSONEmailRequest
to JSON. 不要将
JSONEmailRequest
转换为JSON。 $.post
expects the data argument to be either an object or a string in www-form-urlencoded format. $.post
希望data参数可以是对象,也可以是www-form-urlencoded格式的字符串。 So do: 这样:
$.post("/email.php", JSONEmailRequest, function(data) {
...
}, "json");
And in the PHP code, use $_POST
to get the parameters, and json_encode
to send the result back. 然后在PHP代码中,使用
$_POST
获取参数,并使用json_encode
将结果发送回去。
<?php
$email_to = "shawnandrews@saportfolio.ca";
$email_subject = "User enquiry from ".$_POST['emailaddress'];
$email_body = $_POST['content'];
$result = mail($email_to,$email_subject,$email_body,"From: ".$email_to);
echo json_encode($result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.