这是在WordPress网站上。我使用以下php从输入框中获取用户的电子邮件并将其添加到我的mailchimp列表中。有一个js和php页面可以处理所有繁重的mailchimp内容,但这不应该对我的问题很重要:
<?php
// store-address.php
function storeAddress(){
// Validation
if(!$_GET['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_GET['email'])) {
return "Email address is invalid";
}
require_once('MCAPI.class.php');
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('my-api-key');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "my-list";
if($api->listSubscribe($list_id, $_GET['email'], '') === true) {
// It worked!
return 'Success! Check your email to confirm sign up.';
}else{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
然后在用户输入电子邮件的页面上,它会抓取响应并显示消息结果。这是那部分:
<div id="emailList">
<form id="signup" action="<?=$_SERVER['PHP_SELF']; ?>" method="get" >
<label>signup for our email list</label>
<input type="text" id="email" class="email" name="email" />
<input type="submit" value="OK" id="emailSubmit" name="submit" />
</form>
<script type="text/javascript" src="path/to/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="path/to/js/mailing-list.js"></script>
</div><!-- end emailList -->
<div id="response">
<? require_once('inc/store-address.php');
if($_GET['submit'])
{
echo storeAddress();
} ?>
</div><!-- end response-->
<script type="text/javascript">
$(document).ready(function() {
$("#emailSubmit").click(function() {
$('#response').fadeIn(1500).delay(3500).fadeOut(1500);
});
});
</script>
我的问题很简单。我怎样才能实现某些东西,如果它成功了,它会返回消息&#34;成功!查看您的电子邮件以确认注册。&#34;它只是清除输入框的值而不是预先填充它?输入框ID是&#34;电子邮件&#34;。
我想我需要以某种方式使用。val("")
,但我不知道如果电子邮件成功,我怎么能清除它。
答案 0 :(得分:1)
一个简单的解决方案是:
PHP
if($api->listSubscribe($list_id, $_GET['email'], '') === true) {
// It worked!
return '<span class="success">Success! Check your email to confirm sign up.</span>';
}else{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
JS
$(document).ready(function() {
if($('.success').length > 0) {
$('#email').val('');
}
});
编辑:完整的ajax解决方案
$(document).ready(function() {
var clearOnSuccess = function() {
if ($('.success').length > 0) {
$('#email').val('');
}
};
clearOnSuccess();
$('#signup').submit(function() {
var data = $(this).serializeArray();
data.push({'name': 'ajax', 'value': 1});
var jqXHR = $.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: data
});
jqXHR.done(function(data) {
$('#response').html(data).fadeIn(1500).delay(3500).fadeOut(1500);
clearOnSuccess();
});
return false;
});
});