2012-11-04 120 views
0

我正在尝试构建订阅表单。我无法在我的网站上运行PHP,并且我不希望用户离开主站点订阅通讯。我正在使用this example as server side。 如果您尝试向您发送电子邮件,您将收到重定向,即使电子邮件已添加到mailchimp列表中,也会显示错误消息。Ajax不显示服务器响应

<div id="email"> 
<span>Your email..</span> 
<form action="http://simondahla.com/jolliassets/notify.php" id="notify" method="POST"> 
    <input type="text" placeholder="[email protected]" name="email" id="address" data-validate="validate(required, email)"/> 
    <span>We'll never spam or give this address away</span> 
    <button type="submit">&#187;</button> 
</form> 
<span id="result"></span> 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> 
<script type="text/javascript"> 
$(document).ready(function() { 
    $('#notify').submit(function() { 
     var action = $(this).attr('action'); 
     $.ajax({ 
      url: action, 
      type: 'POST', 
      data: { 
       email: $('#address').attr('value') 
      }, 
      success: function(data){ 
       $('#result').html(data).css('color', 'green'); 
      }, 
      error: function() { 
       $('#result').html('Sorry, an error occurred.').css('color', 'red'); 
      } 
     }); 
    }); 
}); 
</script> 

live example of the problem

+0

[途径可能重复绕过同源政策](http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy) – Quentin

+0

Wher e是实际添加到mailchimp的代码? –

回答

1

您需要从您提交处理程序返回false。这是为了防止浏览器执行默认操作,即以正常方式提交表单。

$('#notify').submit(function() { 
    // .. your ajax call 
    return false; 
}); 
+0

谢谢!所以我改变了。所以我不会被重定向到服务器,但是我能否以某种方式将服务器响应消息传递给客户端?不,它只是说,错误的一切,我尝试。 – Simon

1

从你的PHP函数你要返回你想要给出的代码的成功或失败的值。

成功:

print json_encode(array("status"=>"success","message"=>'Successfully added')); 

失败:

print json_encode(array("status"=>"error","message"=>'There was an error')); 

然后在HTML返回该消息是这样的:

success: function(data){ 
      $('#result').html(content.message).css('color', 'green'); 
     }, 
     error: function() { 
      $('#result').html(content.message).css('color', 'red'); 
     } 
+0

服务器将东西写入数据库,但我没有得到任何回应。使用提供的代码。实际上我没有收到任何回应。 – Simon

+0

你从哪里得到印刷品? –