【问题标题】:Sending value of radiobutton using ajax to node.js使用 ajax 将单选按钮的值发送到 node.js
【发布时间】:2015-03-07 21:28:15
【问题描述】:

我正在尝试使用 Ajax 将单选按钮的值发送到我的 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!");
};

【问题讨论】:

    标签: javascript ajax express


    【解决方案1】:

    首先,我建议使用 jQuery 的强大功能,而不是更冗长的 for-loop 和 document.getElementsByName,反正你在 AJAX 中使用它,为什么不用于选择无线电输入?

    关于单选价值。问题是根据您的代码,您在页面上有多个 id,而 id 必须是唯一的。这就是您可以可靠地读取 checked 输入值的方法:

    $('[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。您需要将其包装到匿名函数中。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 2013-03-26
    • 2015-06-17
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    相关资源
    最近更新 更多