我正在创建一个投票应用程序,我遇到了一个问题,我不知道如何解决。我认为我刚刚构造了我的应用程序。我有一个像这样同时向同一路由发出两个不同的POST请求
app.route('/poll-create')
.post(function(req, res) {
var userID; //variable to store the authentication id for the user
var incoming_id = Object.keys(req.body)[0];
console.log(incoming_id);
serverHandler.newPoll(req, res, db, function(id) {
user_id = id;
});
res.redirect('/new-poll');
});
我传递某种形式的数据,这条路线,像这样从HTML
<form action='' method='post' enctype='multipart/form-data' name='new-poll-form'>
<div class='form-group'>
<label>Title</label>
<input type='text' name='title' class='form-control' placeholder='Title' />
</div>
<div class='form-group'>
<label>Options</label>
<textarea class="form-control poll-options" rows="5" placeholder='Options' name='options'></textarea>
</div>
<button type='submit' class='btn btn-primary submit-butt'>Submit</button>
</form>
在表单中输入的数据直接发送到路线没有一个POST路线我需要一个AJAX请求。我认为这是因为我在表单中设置了method ='post'。
现在,我的问题是,我还需要传入链接到上述HTML文件的JavaScript文件中的对象。我做的是通过AJAX调用像这样
$('.submit-butt').on('click', function() {
console.log('From in here');
ajaxFunctions.ready(ajaxFunctions.ajaxRequest('POST', appUrl + '/poll-create', response.authResponse.userID, function(data) {
}));
});
这里是低于
'use strict';
var appUrl = window.location.origin;
var ajaxFunctions = {
ready: function ready (fn) {
if (typeof fn !== 'function') {
return;
}
if (document.readyState === 'complete') {
return fn();
}
document.addEventListener('DOMContentLoaded', fn, false);
},
ajaxRequest: function ajaxRequest (method, url, data, callback) {
var xmlhttp = new XMLHttpRequest();
console.log('Inside ajaxRequest');
console.log(data);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
callback(xmlhttp.response);
}
};
xmlhttp.open(method, url, true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(data);
}
};
所以AJAX功能,我面对的第一个问题是,当我尝试CONSOLE.LOG通过发送的数据AJAX请求(假设我发送一个对象),我得到的输出是{'object Object':''}。这就是为什么我选择仅从该对象发送用户ID的原因。在这种情况下,我得到这个{'userID':''}。它很烦人,但我至少可以用它工作。
我的第二个问题是,即使我用我的方式解决第一个问题,我实质上是对相同的路由进行两个AJAX调用。所以,我无法同时访问表单数据和用户标识。所以,我不能将它们插入到单个文档中。我如何解决这个问题?有没有更好的方式来传递数据比我目前做的更好?请帮忙! 我正在使用身体分析器来解析传入的数据和强大的解析传入的表单数据。
对于第一个问题,使用的console.log(JSON.stringify(对象)),以对象转换为可读的JSON。 – vlatkokaplan
你从哪里得到response.authResponse.userId?这是否取决于第一次通话? – mimarcel
@vlatkokaplan - 那不行。当我尝试时,它返回{“object Object”:“”},这是我刚才处理的完全相同问题的JSON表示。 –