我希望这是一个简单的问题.我正在使用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"}]}
jQuery的
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文件来验证并提交表单.使用jQuery脚本而不是我的javascript时,html和PHP可以提交表单,这意味着我的脚本有问题,但是我对javascript太陌生,无法完全理解我要做什么.我做错了.
谢谢!
编辑2:
<?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){
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。