这对所有用户来说也不会发生,但会发生的是:
POST请求:
var subscribeD = function(){
console.log("Subscribed function running");
var data = $('#subscribe-form2').serialize();
var emaildata = $('#subscribe-form2').serializeArray();
var email = '';
var download = "";
var downloadvalue = "";
var downloadvaluedesktop = "";
var linkvalue = "";
var linktestvalue = "";
var istakeawaylink = 'FALSE';
var subscribeissuccess = 'FALSE';
$('#subscribe-message2').html('Please wait...');
$("#subscribe-form2 :input").prop("disabled", true);
var i = 0;
while (i < emaildata.length){
if (emaildata[i].name == 'email'){
email = emaildata[i].value;
}
i++
}
var i = 0;
while (i < emaildata.length){
if (emaildata[i].name == 'download-type'){
download = emaildata[i].value;
}
i++
}
var i = 0;
while (i < emaildata.length){
if (emaildata[i].name == 'downloadvalue'){
linktestvalue = emaildata[i].value.substring(0, 4);
//console.log("linktestvalue = " + linktestvalue);
//console.log("Passed from prismic = " + emaildata[i].value);
if (linktestvalue == 'http'){
linkvalue = emaildata[i].value;
istakeawaylink = 'TRUE';
console.log("Identified Link");
} else {
downloadvalue = '/assets/files/' + emaildata[i].value;
downloadvaluedesktop = emaildata[i].value;
}
}
i++
}
$.ajax({
type: "POST",
url: "/subscribe",
data: data,
success: function(data){
$("#subscribe-form2 :input").prop("disabled", false);
if(data.success){
subscribeissuccess = 'TRUE';
LoadUsersFile(download, istakeawaylink, linkvalue, downloadvalue, downloadvaluedesktop);
console.log("Subscribe is Success");
} else {
$('#subscribe-message2').html('Error occurred during subscribe. Please try again later.');
console.log("Else Error Message Triggered");
}
}, error: function(){
console.log("Error Triggered");
$("#subscribe-form2 :input").prop("disabled", false);
$('#subscribe-message2').html('Error occurred during during subscribe. Please try again later.');
}
});
}
服务器端:
module.exports = function(req, res){
var emailId = req.body.email;
var button = req.body.subscribe;
var api = require('../api');
var apikey = "removed";
var listid = "removed";
var body = JSON.stringify({apikey: apikey, id: listid, email: {'email': emailId}, merge_vars:{groupings:[{name:"MERGE1", groups:[button]}]}, double_optin: false, send_welcome: false}),
link = "/2.0/lists/subscribe.json";
api.call(link, body, function(data){
try{
var ret = JSON.parse(data);
console.log(data);
if(ret.leid && ret.euid) res.json({success: true});
else if(ret.code && ret.code == 214) res.json({success: true});
else res.json({success: false});
} catch(e){
res.json({success: false});
}
}, function(err){
res.json({success: false});
});
};
&#34; ... / api&#34;
的代码module.exports = {
call: function (endpoint, body, callback, errcallback){
var http = require('https');
var options = {
host: 'us5.api.mailchimp.com',
post: 443,
path: endpoint,
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(body),
accept: '*/*'
},
method: 'POST'};
var req = http.request(options, function(res){
console.log('STATUS:' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
var data = '';
res.on('data', function(chunk){
data = data + chunk;
});
res.on('end', function(){
callback(data);
});
});
req.on('error', function(e){
console.log('problem with request: ' + e.message);
errcallback(e);
});
req.write(body);
req.end();
}
};
HTML表单:
<form id="subscribe-form2" method="post" action="#">
<div class="row">
<input type="hidden" name="subscribe" value="left-button">
<input type="hidden" name="download-type" value="article-takeaway">
<input type="hidden" name="downloadvalue" value="<%- takeawaydownloadfilename %>">
<input type="email" name="email" placeholder="E-mail Address">
</div>
</form>
<input type="button" value="download" id="subscribe-button2">
<div class="row" id="subscribe-message2" style="border-bottom: 0px !important; padding: 2px 15px; margin-top: 10px;font-size: 16px;">
</div>
事件触发器:
$('#subscribe-button2').on("click", function(){
subscribeD();
});
来自浏览器的日志:(显示帖子第一次失败时的错误消息):
how-to-achieve-goals-any-time-the-skeptics-guide:368
DevTools failed to parse SourceMap: http://localhost:3000/cleanblog/css/bootstrap.min.css.map
how-to-achieve-goals-any-time-the-skeptics-guide#:1 POST http://localhost:3000/practical-insights/how-to-achieve-goals-any-time-the-skeptics-guide 404 (Not Found)
2Navigated to http://localhost:3000/practical-insights/how-to-achieve-goals-any-time-the-skeptics-guide
jquery.main.js:943 Calling CSSStyleSheet.insertRule() with one argument is deprecated. Please pass the index argument as well: insertRule(x, 0).
addCSSRule @ jquery.main.js:943
(anonymous) @ jquery.main.js:976
j @ jquery-1.11.1.min.js:2
fireWith @ jquery-1.11.1.min.js:2
ready @ jquery-1.11.1.min.js:2
J @ jquery-1.11.1.min.js:2
DevTools failed to parse SourceMap: http://localhost:3000/cleanblog/css/bootstrap.min.css.map
how-to-achieve-goals-any-time-the-skeptics-guide:368
来自服务器的日志:
GET /practical-insights/how-to-achieve-goals-any-time-the-skeptics-guide 304 347ms
GET /cleanblog/css/bootstrap.min.css 304 0ms
GET /cleanblog/css/clean-blog.min.css 304 1ms
GET /assets/css/mediaelementplayer.css 304 1ms
GET /assets/css/mejs-skins.css 304 0ms
GET /assets/css/all.css 304 2ms
GET /assets/css/social-sharing.css 304 1ms
GET /assets/css/fancybox.css 304 2ms
GET /assets/js/jquery-1.11.1.min.js 304 1ms
GET /assets/js/mediaelement-and-player.min.js 304 1ms
GET /assets/js/jquery.sticky.js 304 0ms
GET /assets/js/jquery.main.js 304 1ms
GET /assets/js/mixpanel_scroll_tracker.min.js 304 1ms
GET /assets/images/bg-submit.png 304 1ms
GET /assets/images/favicon/favicon-16x16.png 304 1ms
GET /assets/images/favicon/favicon-96x96.png 304 1ms
GET /assets/images/fancybox/fancybox.png 304 282ms
GET /cleanblog/css/bootstrap.min.css 304 2ms
GET /cleanblog/css/clean-blog.min.css 304 0ms
GET /assets/css/mediaelementplayer.css 304 1ms
GET /assets/css/mejs-skins.css 304 5ms
GET /assets/css/all.css 304 3ms
GET /assets/css/social-sharing.css 304 1ms
GET /assets/css/fancybox.css 304 1ms
GET /cleanblog/css/bootstrap.min.css.map 304 275ms
POST /practical-insights/how-to-achieve-goals-any-time-the-skeptics-guide 404 2ms - 81b
GET /cleanblog/css/bootstrap.min.css.map 304 740ms
GET /assets/images/favicon/favicon-16x16.png 304 4ms
GET /assets/images/favicon/favicon-96x96.png 304 2ms
GET /assets/images/fancybox/fancybox.png 304 336ms
STATUS:200
HEADERS: {"server":"openresty","content-type":"application/json; charset=utf-8","content-length":"64","vary":"Accept-Encoding","date":"Sun, 08 Jan 2017 22:08:35 GMT","connection":"close","set-cookie":["_AVESTA_ENVIRONMENT=prod; path=/"]}
{"email":"ght@gmail.com","euid":"b330aa8ce1","leid":"118430401"}
POST /subscribe 200 308ms - 16b
app.js文件:
/**
* Module dependencies.
*/
var express = require('express'),
favicon = require('static-favicon'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
session = require('express-session'),
cookieSession = require('cookie-session'),
errorHandler = require('errorhandler'),
http = require('http'),
path = require('path'),
prismic = require('./modules/prismic-helpers'),
api = require('./modules/api'),
redisStore = require('connect-redis')(session),
flash = require('connect-flash'),
passport = require('passport');
//bson = require('bson');
var app = express();
var moment = require('moment');
if (process.env.REDISTOGO_URL) {
var rtg = require("url").parse(process.env.REDISTOGO_URL);
var store = new redisStore({
host : rtg.hostname,
port : rtg.port,
pass : rtg.auth.split(":")[1]
});
} else {
var store = new redisStore();
}
// all environments
app.set('port', process.env.PORT || 3100);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//app.use(favicon(path.join(__dirname, 'public', 'assets', 'images', 'favicon.ico')));
app.use(logger('dev'));
app.use(cookieParser());
//app.use(bodyParser());
//app.use(bodyParser.urlencoded({ extended: false }));
//app.use(bodyParser.json());
// app.use(bodyParser.urlencoded());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
//testing updated bodyparser info
app.use(methodOverride());
//app.use(express.session({ secret: secretKey, store: store, cookie: { secure: false, maxAge: 86400000 }, maxAge: 360*5}));
app.use(cookieSession({ secret: "d!30dapdif3", store: store, cookie: { secure: false, maxAge: 86400000 }, maxAge: 86400000}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(errorHandler());
//deals with the issue of blog/ redirecting to some weird page
app.use(function(req, res, next) {
if(req.url.substr(-1) == '/' && req.url.length > 1)
res.redirect(301, req.url.slice(0, -1));
else
next();
});
var strategy = require('./modules/strategy')(passport);
//removed other routes for brevity
app.post("/subscribe", require('./modules/controller/subscribe'));
var PORT = app.get('port');
/*app.listen(PORT, function() {
console.log('Express server listening on port ' + PORT)
});*/
app.listen(3000, function () {
console.log('impaktlabs.com listening on port 3000!')
})
答案 0 :(得分:0)
经过更多试验和错误修复错误。
问题是我的事件处理程序链接到单击提交按钮而不是表单本身,所以“return false;” @jcaron建议,实际上并没有阻止表单的默认提交操作。
我添加了一个链接到代码提交的新处理程序:
$("#subscribe-form2").submit(function(e){
subscribeD();
return false;
});
这解决了这个问题。