为什么我的AJAX调用没有加载?

时间:2010-02-18 23:12:02

标签: jquery ajax api

我正在努力与MailChimp API集成以通过Ajax提交表单,但是我在集成他们提供的表单时遇到了很多麻烦。我认为这是一个很好的机会让我更多地了解Ajax,但我不能为我的生活找出我的电话出错的地方。这是我在Ajax调用中的内容:

 $('#submit-button').click(function(){
  var email = $('input#email').val();
  if(email == "you@address.com"){
   $('p#empty-error').fadeIn();

  return false;
  }

  var datastring1 = 'email=' + email;

  $.ajax({
   type: 'POST',
   url: 'mailchimp/store-address.php',
   data: datastring1,
   success: function(){
    alert('success');
   }
  });

  return false;
 });

要标记的PHP文件:

function storeAddress(){

 // Validation
 if(!$_POST['email']){ return "No email address provided"; } 

 if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_POST['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('66a7f17d87e96e439f7a2837e2963180-us1');

 // 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 = "b1ebe7c0ba";

 if($api->listSubscribe($list_id, $_POST['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($_POST['ajax']){ echo storeAddress(); }
?>

该脚本最初编写为通过Prototype中的Ajax提交,我正在尝试将事情转移到jQuery。我很想知道为了实现这一目标我不理解的事情。

更多信息:如果有任何帮助,如果我在HTML中删除了javascript,则以下调用有效:

<?php require_once('mailchimp/store-address.php'); if($_POST['submit']){ echo storeAddress(); } ?>

2 个答案:

答案 0 :(得分:0)

问题是您正在检查是否设置了名为'ajax'的POST变量,但是只设置了'email'

您可以通过直接检查email来解决此问题:

if($_POST['email']) { echo storeAddress(); }

或者如果页面只有一个操作:

if(isset($_POST)) { echo storeAddress(); }

答案 1 :(得分:0)

唉。使用Ajax时,请勿尝试相对路径。这是我的整个问题。只需将URL指向绝对路径即可。谢谢你的帮助。