在这个例子中,我使用的是MySQL,我知道它已被弃用,但这仅用于学习目的。我也在学习如何使用PDO,现在只是因为我对PDO缺乏经验而不想搞砸,所以我现在正在使用mysql。
好的,所以我有一个jQuery AJAX函数,它将表单数据提交给PHP函数页面。然后,PHP页面与数据库通信并返回结果。到目前为止,这一切都有效。
用户填写提供其电子邮件地址的表单。电子邮件将传递给PHP页面并输入到数据库中。如果用户存在,则会显示一条消息,告知他们已经订阅了这些消息。如果不退出,则会添加它们,然后会显示一条消息,告知它们已成功添加。好消息是这一切都很棒!
现在,我遇到的一个问题是,在同一个回调函数“dispAdd”中,我想为用户生成一个自动欢迎电子邮件。无论我如何尝试编写邮件调用,我似乎在函数中出错。我会给你现在的东西,但如果有人可以提供帮助,那将非常感激。
这是我的回调函数,因为所有其他部分现在都可以正常工作:
function dispAdd() // Serves as callback function to jQuery/AJAX in contact.html
{
$sql= "SELECT * FROM mailList WHERE email = '$email'";
$result= mysql_query($sql) or die(mysql_error());
$to = "rmailloux11@mail.bristol.mass.edu";
$who = "ME";
$message = "WOW";
$subject = "TESTING";
$message = $who . ', ' . $message;
$headers = "From: rmailloux11@mail.bristol.mass.edu" . "\r\n";
if(mysql_num_rows($result) > 0) // Checks to see if query returns any info for the calling function
{
mail($to,$subject,$message,$headers);
while ( $row = mysql_fetch_assoc($result))
return;
}
}
原始来电:
$('#contForm').submit(function() {
var formData = $(this).serialize(); // Stores all form data in AJAX variable
$.post('contact.php',formData,dispAdd);
function dispAdd(result) { // Callback function requests result of RESULT
if (!result) {
$('#main').html('<div>Your have been added to the mailing list</div>');
} else {
if ($('#fail').length==0) {
$('#main').append('<div id="fail" style="color:red";>This email address is already subscribed to our mailing list</div>');
}
}
}
return false; // Stops form from loading contact.php page
});
答案 0 :(得分:1)
<script>
$('#contForm').submit(function()
{
var formData = $(this).serialize(); // Stores all form data in AJAX variable
$.post('contact.php',formData, function(data)
{
console.log(data);
if(data)
{
$('#main').html('<div>You have been added to the mailing list</div>');
}
else
{
$('#main').append('<div id="fail" style="color:red";>This email address is already subscribed to our mailing list</div>');
}
console.log(data);
});
return false; // Stops form from loading contact.php page
});
</script>
然后,在contact.php中你应该放下以下函数:
function dispAdd() // Serves as callback function to jQuery/AJAX in contact.html
{
$sql= "SELECT * FROM mailList WHERE email = '$email'";
$result= mysql_query($sql) or die(mysql_error());
$to = "rmailloux11@mail.bristol.mass.edu";
$who = "ME";
$message = "WOW";
$subject = "TESTING";
$message = $who . ', ' . $message;
$headers = "From: rmailloux11@mail.bristol.mass.edu" . "\r\n";
if(mysql_num_rows($result) > 0) // Checks to see if query returns any info for the calling function
{
mail($to,$subject,$message,$headers);
while ( $row = mysql_fetch_assoc($result))
return;
}
}
在contact.php上的代码运行之后,让它调用dispAdd
函数并将dispAdd
的结果返回给您的Ajax请求。