我在保留当前页面时遇到从HTML表单发送数据到我的PHP页面(通过JS / AJAX)的问题。这就是我目前所拥有的:
HTML部分:
<!-- Begin the Form -->
<form id="signup-form" method="POST">
<!-- Input of E-Mail -->
<div class="seven columns">
<input type="email" name="email" id="email" placeholder="Your E-Mail">
</div>
<!-- Send Button -->
<div class="five columns">
<button name="submit" type="button" class="button">Subscribe</button>
</div>
<!-- End of the Form -->
</form>
PHP:
<?php
require_once 'MCAPI.class.php';
$apikey = 'XXXXXX';
$list_id ='XXXXXX';
$api = new MCAPI($apikey);
$email = $_POST['email'];
echo "Email: ".$email;
$merge_vars = array(' ');
// By default this sends a confirmation email - you will not see new members
// until the link contained in it is clicked!
$retval = $api->listSubscribe( $list_id, $email, $merge_vars );
if ($api->errorCode){
echo "Unable to load listSubscribe()!\n";
echo "\tCode=".$api->errorCode."\n";
echo "\tMsg=".$api->errorMessage."\n";
} else {
echo "E-Mail submitted to the pxCollective Newsletter!";
}
?>
JS:
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var email = $("#email").val();
if(email=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "subscribeEmail.php",
data: email,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
如果我不尝试使用JS / AJAX将其保留在当前页面上,那么它就可以直接进入PHP页面,并将用户订阅到邮件列表。关于我的问题可能是什么想法?
谢谢!
答案 0 :(得分:4)
此行data: email,
应为data: {email: email},
答案 1 :(得分:0)
试试这个
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var email = $("#email").val();
if(email=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "subscribeEmail.php",
data: {email: email}, // don't data: email,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
答案 2 :(得分:0)
您正在使用$('.submit').click()
,但没有类submit
的元素!您的提交按钮是button
类。
您应该使用$('#signup-form').submit()
而是将<button>
更改为<input type="submit">
。
答案 3 :(得分:-1)
尝试
$.ajax({
type: "POST",
url: "subscribeEmail.php",
data: "email="+email,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
应该是&#34; email =&#34; + email