按钮点击调用ajax

时间:2013-05-20 10:00:53

标签: jquery ajax

我有一个简单的html按钮。

当我点击它时,会调用ajax。

这是我的代码。

 <INPUT type="button" class="form6form" id="newsubmit" name="newsubmit" value="Submit">

这是ajax完整代码。

我希望ajax验证我的代码,然后使用成功处理程序

 $('body').on('click', '#newsubmit', function (event) {

    $("#form6").validate({
        debug: false,
        rules: {
            plnonew: "required",
            pldtnew: "required",
            noboxnew: "required",
        },
        messages: {

            plnonew: "Please select a pack list id..",
            pldtnew: "Please select a date..",
            noboxnew: "Please select a box no..",
        },
        submitHandler: function (form) {
            $.ajax({
                type: "POST",
                url: "try.php",
                data: $('#form6').serialize(),
                cache: false,

                success: function (html) {

                    var div1 = $(html).filter('#div1');

                    loading_hide();
                    $("#container").html(div1);
                }
            });
        }
    });

});

单击按钮时没有任何反应。

有什么想法吗?谢谢。

2 个答案:

答案 0 :(得分:4)

在html代码客户端侧index.html文件

<!doctype html>
<html>
    <head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>

    function myCall() {
        var request = $.ajax({
            url: "ajax.php",
            type: "GET",            
            dataType: "html"
        });

        request.done(function(msg) {
            $("#mybox").html(msg);          
        });

        request.fail(function(jqXHR, textStatus) {
            alert( "Request failed: " + textStatus );
        });
    }
</script>
        <meta charset="utf-8" />
        <title>My jQuery Ajax test</title>
        <style type="text/css">
            #mybox {
                width: 300px;
                height: 250px;
                border: 1px solid #999;
            }
        </style>
    </head>
    <body>
        The following div will be updated after the call:<br />
        <div id="mybox">

        </div>
        <input type="button" value="Update" />

    </body>
</html>

在服务器端ajax.php文件

<?php
echo '<p>Hi I am some random ' . rand() .' output from the server.</p>';

?>

答案 1 :(得分:2)

验证插件中的submitHandler会替换原生提交,类型为button的输入将不会提交表单并触发sumbitHandler,因此请更改此内容:

<INPUT type="button" class="form6form" id="newsubmit" name="newsubmit" value="Submit">

为:

<input type="submit" class="form6form" id="newsubmit" name="newsubmit" value="Submit">

并在点击处理程序之外初始化验证。