我在 AngularJS 中创建了一个应用程序,它有一个电子邮件联系表单,它使用服务器中的 PHP 文件发送电子邮件。
这是我在 AngularJS 中的 Controller.js 部分:
$scope.feedbacksubmit= function (){
var name1 = document.getElementById("name").value;
var email1 = document.getElementById("email").value;
var message1 = document.getElementById("message").value;
$http({
url: "http://boost.meximas.com/mobile/email.php",
method: "POST",
data: { name: name1, email: email1, message:message1 }
}).success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
if(status == 200) {
var return_data = data;
if(return_data != 0){
$scope.hide();
//$scope.closeFeedback();
}else{
$scope.showEmailError();
}
}
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log(status);
$scope.showAlertNetwork();
$scope.hide();
});
};
这是我的 PHP 代码:
<?php
$array = json_decode(file_get_contents('php://input'), true);
$name = $array['name'];
$email = $array['email'];
$message = $array['message'];
if (($name=="")||($email=="")||($message==""))
{
printf("0");
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("mygmail@gmail.com", $subject, $message, $from);
}
?>
当我填写联系表格并点击“发送”按钮时出现问题。我收到 $scope.showEmailError();
。但我收到电子邮件没有问题。
如果我尝试在不填写表单的情况下点击按钮,仍然会收到相同的 $scope.showEmailError();
消息。
最佳答案
为什么不使用来自输入的模型值?看起来您尝试使用 AngularJS,但您仍然在考虑其他框架
在下面的示例中,我将模型发送到 php 脚本,如果 NAME 未填写,则 PHP 返回 404 错误,它在 AngularJS $http
中通过 .error
进行处理处理程序。你不必为 success 添加那么多额外的逻辑来处理它
http://plnkr.co/edit/sw9RRXb3kdEWXszJdwX3?p=preview
html
<input type="text" ng-model="formData.name" placeholder="name">
<input type="text" ng-model="formData.email" placeholder="email">
<input type="text" ng-model="formData.message" placeholder="message">
JavaScript
$scope.formData = {
'name': '',
'email': '',
'message': ''
};
$scope.postData = function () {
$http.post('http://edeen.pl/form.php', $scope.formData)
.success(
function(data){
$scope.response = data.replace(/\ /g, ' ').replace(/\n/g, '<br/>') //format response
})
.error(
function(data){
$scope.response = data
})
}
php
$input = json_decode(file_get_contents('php://input'));
if($input->name === ''){
header("HTTP/1.0 404 Not Found");
echo "Something went terribly wrong, missing name maybe?";
return;
}
header('Content-Type: application/json');
var_dump($input);
关于javascript - 使用 AngularJS 和 PHP 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30817506/