【发布时间】:2016-05-13 13:41:58
【问题描述】:
我的 html 中有这个 javascript 代码。
answers.push({
answer:$('#answer_1').val(),
correctAnswer:$('#choice_1').is(":checked")
});
questions.push({
questionNumber:1,
questionType:questionType,
questionText:questionText,
answers:answers
});
$('.hiddenField').val(JSON.stringify(questions));
如您所见,我在问题数组中有答案数组。我想将此问题数组传递给服务器端 javascript 文件。我正在尝试在 HTML 表单的 POST 方法中使用隐藏输入来执行此操作,如下所示。
<form action="/new" method="POST">
<div class = "quiz_basic">
<input type = "hidden" class = "hiddenField" name = "questions" />
</div> </form>
在服务器端 js 文件中,当我尝试使用 req.body.questions 参数访问它时,我收到“unexpected token u”错误。这是我的服务器端代码。我正在使用 nodejs 框架。
router.post('/new', function(req, res, next){
var questions = JSON.parse(req.body.questions);
console.log('Question array is ', questions);
var answers = JSON.parse(req.body.questions.answers);
console.log('Answer array is ', answers);
res.send('success');
}
如果我从 questions 数组中删除 answers 数组对象并仅通过 HTML POST 方法传递它,我可以毫无问题地解析它。我应该如何通过 HTML 发送一个将另一个数组作为其元素之一作为一个对象的数组?各位大神能帮帮我吗?
questions.json 看起来像这样
[{"questionNumber":1,"questionType":"radio","questionText":"Whats your name","answers":[{"answer":"Peter","correctAnswer":true},{"answer":"Dave","correctAnswer":false},{"answer":"Adam","correctAnswer":false},{"answer":"Steve","correctAnswer":false}]}]
如上所述,如果我删除“answers”数组并发送它,它不会在服务器端引发错误。
谢谢
【问题讨论】:
-
请修正您的 HMTL 格式:
... <div class="quiz_basic"><input type="hidden" class="hiddenField" name="questions" /> ... -
你能写出完整的错误堆栈跟踪吗?
-
可以通过AJAX(XmlHttpRequest)提交给服务器JS数组和对象。它有很多方便的包装器,例如在 jQuery 中。
-
你能发帖,关于 json 的问题是什么样的吗?
-
用更多细节编辑了我的帖子。添加了 questions.json,格式化为 html
标签: javascript html node.js forms associative-array