我有一个 PHP 电子邮件表单,用户输入他们的电子邮件,然后它会向他们发送指向他们上传的文件的链接。我如何使用 AJAX 提交该表单?
现在,我可以让他们点击链接转到包含电子邮件表单的页面,并且我在 URL 中传递 $target_path
变量,以便链接到上传的文件可以在电子邮件中。这是我在“成功上传”页面上转到 email.php
的 PHP:
<?php echo "<a href='email.php?target_path=".$target_path."'>Click here</a> to get the link sent to your email." ?>
这是email.php
的来源:
<html>
<head>
<title>Upload File</title>
<style type="text/css">
body {
font-family:arial,sans-serif;
}
.error {
color:red;
}
</style>
</head>
<body>
<?php
function spamcheck($field)
{
//filter_var() sanitizes the e-mail
//address using FILTER_SANITIZE_EMAIL
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail
//address using FILTER_VALIDATE_EMAIL
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_REQUEST['email']))
{//if "email" is filled out, proceed
//check if the email address is invalid
$mailcheck = spamcheck($_REQUEST['email']);
if ($mailcheck==FALSE)
{
echo "Invalid email, please try again.";
}
else
{//send email
$to = $_REQUEST['email'] ;
$subject = "Your file has been uploaded to our site and here's a link to it" ;
$message = "
Hello,
Your file has been uploaded to our site. Here is a link to it for future reference, keep this email if you want to remember the link to your file: http://www.example.com/upload/".$_REQUEST['target_path']."
Thank you.";
mail($to,$subject,$message, "From: noreply@example.com" );
echo "Email has been sent. Please check your inbox and/or spam folder.";
}
}
else
{//if "email" is not filled out, display the form
echo "<form method='post' action=''>
Email: <input name='email' type='text' /><br /><br />
<input type='submit' />
</form>";
}
?>
</body>
</html>
如您所见,当他们单击链接转到“成功上传文件”页面 (upload.php
) 上的 email.php
时,它会传递 $target_path
变量,因此它将能够发送指向上传文件的链接。
我想将电子邮件表单放在 upload.php
(文件上传表单提交到的页面)上,然后使用 jQuery AJAX 提交该电子邮件表单。我只是不知道如何让它发挥作用。我还需要仍然传递该变量,但我认为它不会出现在 URL 中,它可能位于 AJAX 代码中的其他位置。
非常感谢任何帮助。
谢谢,
内森
最佳答案
下面是JS代码
$(document).ready(function(){
$('#emailbtn').click(function(){
//This is short form of php echo
var target_path = <?php=$target_path?>
//Get eMail from input
var email = $('#email').val();
//Send form to email.php using GET method
$.ajax(
{
type: "GET",
url: "email.php",
data: ({"target_path" : target_path, "email" : email}),
success: function(message)
{
$("#btnspan").empty().append(message);
}
});
});
});
这是一段 HTML 代码
<span id="btnspan">Your eMail: <input type="text" name="email" id="email" /> <button id="emailbtn" class="button">eMail me the link</button></span>
看来你的email.php返回了有效的消息,所以当你点击按钮时会发生什么,你的php提供的内容将替换表单内容!页面不刷新。
我建议您更改的一件事是 GET 方法,将其更改为 POST!对于 php,我假设您知道它是 $_POST[varname]
来检索值,对于 JS,只需将 AJAX 类型更改为 POST 即可。
关于php - 如何使用 jQuery AJAX 提交此表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6951559/