【发布时间】:2017-05-17 06:27:21
【问题描述】:
很抱歉,如果这是重复之前的问题,但我无法找到似乎可以解决我的问题并且我是 Angular 新手的解决方案。
我有一个 Angular 表单,它与 PHP 通信数据以发送电子邮件,而我的问题是处理来自 PHP 的 JSON 响应(因为 PHP 会在 JSON 本身内返回它是否成功,以及一条消息) . 我似乎无法让代码根据 JSON 中包含的“成功”值做出响应,也无法实际显示“消息。
所以我的 Angular 代码需要根据“成功”是真还是假来做出响应,同时还要显示由 AJAX 以 JSON 格式传递的“消息”。
我的 Angular 控制器代码:
app.controller('ContactController', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false;
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
var request = $http({
method : 'POST',
url : 'php/contact.php',
data : $.param($scope.formData), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
});
if (request.success) {
console.log(request);
$scope.submitButtonDisabled = false;
$scope.result='bg-success';
$scope.resultMessage = request.message;
} else {
$scope.submitButtonDisabled = true;
$scope.resultMessage = request.message;
//$scope.resultMessage = "Opps!... something went wrong. Please Contact OpenHouse directly to let them know of this error.";
$scope.result='bg-danger';
};
//};
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed <img src="http://www.chaosm.net/blog/wp-includes/images/smilies/icon_sad.gif" alt=":(" class="wp-smiley"> Please fill out all the fields.';
$scope.result='bg-danger';
}
}
});
我的 PHP 代码:
<?php
require_once ("class.phpmailer.php"); // Include phpmailer class
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
if (isset($_POST['inputFirstName']) && isset($_POST['inputLastName']) && isset($_POST['inputEmail']) && isset($_POST['inputPhone']) && isset($_POST['inputMessage'])) {
//check if any of the inputs are empty
if (empty($_POST['inputFirstName']) || empty($_POST['inputLastName']) || empty($_POST['inputEmail']) || empty($_POST['inputPhone']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
$message=
'First Name: '.$_POST['inputFirstName'].'<br />
Last Name: '.$_POST['inputLastName'].'<br />
Phone: '.$_POST['inputPhone'].'<br />
Email: '.$_POST['inputEmail'].'<br />
Comments: '.$_POST['inputMessage'].'
';
$mail = new PHPMailer(); // Instantiate the PHPMailer Class
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // SMTP authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled + REQUIRED for Gmail (either SSL or TLS)
$mail->Host = "smtp.gmail.com"; //Gmail SMTP Server to relay thru
$mail->Port = 465; // Port 465 as we're using SSL... or use Port 587 for TLS
$mail->IsHTML(true); // We're sending a HTML formatted message
$mail->Username = "....@gmail.com"; // Gmail account for authentication
$mail->Password = "*********"; // Gmail password for authentication
$mail->SetFrom("....@gmail.com"); // The email is being sent from this address
$mail->Subject = "Website Contact Form Enquiry"; // The subject line of the email
$mail->Body = ($message); // The actual email message to be sent
$mail->AddAddress("....@gmail.com"); // The email is being sent to this address
if(!$mail->send()) {
echo json_encode(['success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo]);
exit;
}
error_log("Data: ".$data['success']." Message: ".$data['message']);
echo json_encode(['success' => true, 'message' => 'Thanks! We have received your message.']);
} else {
echo json_encode(['success' => false, 'message' => 'Please fill out the form completely.']);
}
?>
【问题讨论】:
-
了解$http 服务。 $http 不返回响应正文,它返回一个带有响应对象的承诺,其中包含响应正文以及其他内容,例如标头、状态等。
-
另外,为了让 Angular 自动解析您从 PHP 到对象而不是 JSON 字符串的响应,您应该在响应中返回
content-type: application/json标头, -
@BlissSol 扩展了 Ron Dadon 的答案,因为
$http是异步的,并且request变量返回一个承诺,而不是if (request.success)你会想要request.then( function(response) { if (response.data.success) { ... } } )
标签: php angularjs json ajax angularjs-http