草庐IT

javascript - 通过 Mailchimp 返回错误、Javascript 和 php 提交电子邮件

coder 2024-05-05 原文

我希望这是一个简单的问题。我正在使用 Mailchimp API 从我的网站提交一个简单的电子邮件注册表单。我现在正在尝试学习 javascript,所以我正在尝试在没有 jQuery 的情况下执行 httprequest 和回调。基本上,我正在尝试将我在网上找到的这个 jQuery 示例转换为 vanilla Javascript。但是我的 javascript 有一些(几件事?)我不明白的错误。

编辑:提交表单后,我被带到 email-validate.php 页面,并显示 MailChimp 返回的以下错误对象。

{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"Invalid Resource","status":400,"detail":"The resource submitted could not be validated. For field-specific details, see the 'errors' array.","instance":"","errors":[{"field":"","message":"Required fields were not provided: email_address"},{"field":"email_address","message":"Schema describes string, NULL found instead"}]}

j查询

Found here (这实际上抛出一个 ajax(...)。成功不是控制台中的函数错误,但仍然提交表单,FWIW)

$('document').ready(function(){
  $('.mc-form').submit(function(e){

    //prevent the form from submitting via the browser redirect
    e.preventDefault();

    //grab attributes and values out of the form
    var data = {email: $('#mc-email').val()};
    var endpoint = $(this).attr('action');

    //make the ajax request
    $.ajax({
      method: 'POST',
      dataType: "json",
      url: endpoint,
      data: data
    }).success(function(data){
      if(data.id){
        //successful adds will have an id attribute on the object
        alert('thanks for signing up');
      } else if (data.title == 'Member Exists') {
        //MC wil send back an error object with "Member Exists" as the title
        alert('thanks, but you are alredy signed up');
      } else {
        //something went wrong with the API call
        alert('oh no, there has been a problem');
      }
    }).error(function(){
      //the AJAX function returned a non-200, probably a server problem
      alert('oh no, there has been a problem');
    });
  });
});

我的 Javascript(不起作用)

document.addEventListener("DOMContentLoaded", function() {
    document.getElementById("mc-form", function submit(e){
        e.preventDefault();

        var data = {"email": document.getElementById("mc-email").value};
        var endpoint = document.getElementById("mc-form").getAttribute('action');

        function formSubmit(callback){
            var request = new XMLHttpRequest();

                request.onreadystatechange = function() {
                    if (request.readyState === 4) {
                      if (request.status === 200) {
                        //Parse returned string into an object, then pass the object to the callback function.
                        var response = JSON.parse(request.responseText);
                        callback(response);
                      } else {
                   console.log('JSON request error');
                        }
                    }
                }
            request.open("POST", endpoint , true);
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            request.send(data);
        }
        function formResponse(response){
            if(response.id){
            //successful adds will have an id attribute on the object
            alert('Thank you for signing up for Launch Alerts!');
          } else if (response.title == 'Member Exists') {
            //MC wil send back an error object with "Member Exists" as the title
            alert('You are already signed up for Launch Alerts!');
          } else {
            //something went wrong with the API call
            alert('Something went wrong. Please resubmit the form!');
          }
        }
        formSubmit(formResponse);
    })
});

我的html

<form class="mc-form" method="POST" action="./email-validate.php">
    <h2 class="launch-alerts">Never miss a launch with Launch Alerts</h2>
    <label for="mc-email">Email Address:</label>
    <input type="email" id="mc-email" name="mc-email" autofocus="true" required/>
    <input type="text" value="pending" id="status" name="status" hidden/>
    <input type="submit" value="Submit">
</form>

它使用一个 php 文件来验证和提交表单,如上面的链接所示。 html 和 php 在使用 jQuery 脚本时提交表单,但不是我的 javascript,这意味着我的脚本有问题,但我对 javascript 太陌生了,无法完全理解我正在尝试做什么,并且我做错了什么。

谢谢!

编辑 2:

PHP代码(直接复制自here

<?php
//fill in these values for with your own information
$api_key = 'xxxxxxxxxxxxxxxxxxxxxxxx';
$datacenter = 'xxxxx';
$list_id = 'xxxxxxxxx';
$email = $_POST['email'];
$status = 'pending';
if(!empty($_POST['status'])){
    $status = $_POST['status'];
}
$url = 'https://'.$datacenter.'.api.mailchimp.com/3.0/lists/'.$list_id.'/members/';
$username = 'apikey';
$password = $api_key;
$data = array("email_address" => $email,"status" => $status);
$data_string = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$api_key");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;
?>

最佳答案

request.send() 的数据参数必须是 URL 编码的字符串,您正在传递一个对象。 jQuery 会自动为你做这个转换;当你自己做的时候,你也必须自己做。

var data = "email=" + encodeURIComponent(document.getElementById("mc-email").value);

您也没有将提交函数正确添加到表单的 submit 事件中。应该是:

document.getElementById("mc-form").addEventListener("submit", function submit(e){

关于javascript - 通过 Mailchimp 返回错误、Javascript 和 php 提交电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39105029/

有关javascript - 通过 Mailchimp 返回错误、Javascript 和 php 提交电子邮件的更多相关文章

  1. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  2. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  3. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  4. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  5. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  6. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  7. ruby-on-rails - Enumerator.new 如何处理已通过的 block ? - 2

    我在理解Enumerator.new方法的工作原理时遇到了一些困难。假设文档中的示例:fib=Enumerator.newdo|y|a=b=1loopdoy[1,1,2,3,5,8,13,21,34,55]循环中断条件在哪里,它如何知道循环应该迭代多少次(因为它没有任何明确的中断条件并且看起来像无限循环)? 最佳答案 Enumerator使用Fibers在内部。您的示例等效于:require'fiber'fiber=Fiber.newdoa=b=1loopdoFiber.yieldaa,b=b,a+bendend10.times.m

  8. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  9. ruby - 检查字符串是否包含散列中的任何键并返回它包含的键的值 - 2

    我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案

  10. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

随机推荐