我正在尝试使用Ajax将radiobutton的值发送到我的express / node应用程序,但我遇到了问题(我是ajax的新手)。关于这个主题还有其他一些帖子,但我似乎无法让我的工作。我正在创建一个多项选择问题应用程序,并希望发送所选答案的值。这是我的js脚本:
lockAnswer = function(value) {
var x = document.getElementsByName("answer");
for ( i = 0; i < x.length; i ++ ) x[i].disabled = true;
document.getElementById("explanation").style.display = "";
$.ajax({
type: "POST",
url: window.location.pathname,
data: { "value": document.getElementById('answer').value },
success: alert(1),
error: alert(0)
});
};
答案已锁定,但未发送成功消息或错误消息。我的节点代码是:
app.post('/test/:username/:testid/:noq/:quesnum', users.answer_selected);
module.exports.answer_selected = function (req,res) {
console.log("Made it!");
};
答案 0 :(得分:0)
首先,我建议使用jQuery的功能,而不是使用document.getElementsByName
更详细的for循环,无论如何使用它进行AJAX,为什么不使用它来选择无线电输入?
关于无线电价值。问题是根据您的代码,您在页面上有多个ID,而id必须是唯一的。这是您可以可靠地读取已检查输入值的方法:
$('[name=answer]:checked').val()
改进的功能变为:
lockAnswer = function(value) {
$('[name=answer]').prop('disabled', true);
$('#explanation').css('disaply', '');
$.ajax({
type: "POST",
url: window.location.pathname,
data: { "value": $('[name=answer]:checked').val() },
success: function() { alert(1) },
error: function() { alert(0) }
});
};
还有另一个问题。此代码success: alert(1)
将无法按预期工作,因为success
需要函数引用,但alert(1)
会立即执行并返回undefined
。你需要把它包装成一个无穷无尽的函数。