0

以下 JQuery“表单”有效(通过 ajax 发送和接收数据)但如果我更改

 <div id="formContact">

form标签,然后它不起作用。为什么是这样?

<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>Testing - Test</title>
        <meta name="keywords" content="" />
        <meta name="description" content="" />
        <script type="text/javascript" src="systemJavascript/jquery-1.4.4.min.js"></script>
        <style type="text/css">

            #result {
                margin: 10px;
                background: #eee;
                padding: 10px;
                height: 40px;
                overflow: auto;
            }
        </style>
        <script type="text/javascript">
            $(function() {
                $('#resultArea').html('click button');
                $('button#formButton').click(function() {
                    console.log('we only get here if form is a DIV element, not a FORM element');
                    $('button#formButton').blur();
                    $('#firstName').focus();
                    $.post(
                    'testAjaxProcess2.php',
                    {
                        firstName: $('#firstName').val(),
                        lastName: $('#lastName').val()
                    },
                    function( jsonString )
                    {
                        var data = $.parseJSON(jsonString);
                        $('div#resultArea').html(data['message']);
                    });
                });
            });

        </script>
    </head>
    <body>
        <h2>Form</h2>
        <div id="formContact">
            <div>First Name:<input type="text" id="firstName"/></div>
            <div>Last Name:<input type="text" id="lastName"/></div>            
            <div><button id="formButton">Send</button></div>
        </div>
        <h2>Result</h2>
        <div id="resultArea">
        </div>
    </body>
</html>
4

1 回答 1

5

最佳猜测 - 默认情况下 abutton将充当表单的提交按钮。您想阻止单击处理程序中的默认操作来停止此操作:

$('button#formButton').click(function(e) { // assign event object
  e.preventDefault( ); // Stop the form being submitted.
  console.log('we only get here if form is a DIV element, not a FORM element');
});

编辑:我刚刚用 jsfiddle 确认了这一点:http: //jsfiddle.net/Y2MdZ/

于 2012-11-16T13:16:42.047 回答