麻烦使用onClick提交表单的ajax脚本

时间:2015-02-15 10:17:21

标签: javascript php jquery forms

我在页面上有几个表单,使用jquery / ajax从单选按钮提交值。使用“提交”按钮时,一切正常,但我想取消“提交”按钮。我尝试使用onClick提交。但是,以这种方式尝试会导致在处理脚本提取表单之前提交表单。我非常感谢建议(如果可能,我会非常感谢)。谢谢你,Brian

脚本:

$(document).ready(function() {

// process the form
$('form').submit(function(event) {


    // get the form data
    var formData = $(this).serialize();

    // process the form
    $.ajax({
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : 'process.php', // the url where we want to POST
        data        :  formData, // our data object
        dataType    : 'json' // what type of data do we expect back from the server


    })
        // using the done promise callback
        .done(function(data) {

        if (data.success) {
            // success.
            // hide form container          
            $("#"+data.message).hide();
            $("#"+data.message+"hr").hide();
        }

            // log data to the console so we can see
            //console.log(data); 

            // here we will handle errors and validation messages
        });

    // stop the form from submitting the normal way and refreshing the page
    event.preventDefault();
});

});

形式:

<method="post" action="process.php" enctype="multipart/form-data">
<input type="radio" name="answer" value="yes" onClick="onClick="this.form.submit()">

1 个答案:

答案 0 :(得分:0)

你的onclick语法错误,但在元素上加上onclick属性是一种过时的做事方式。

您可能希望处理change事件而不是click,因为在点击后选择了radiobutton,因此如果您立即提交表单,则可能尚未选择radiobutton(我不确定,我必须进行实验,但change可能更加万无一失。)

$(document).ready(function() {
    $('input[type=radio]').change(function(event) {
        //the rest of your code goes here
        //you don't need event.preventDefault() anymore
    });
});

编辑:$(this)当然不会再引用该表单,只需将其替换为$('form')即可。