jQuery AJAX事件preventDefault()对表单提交不起作用

时间:2019-10-29 02:17:26

标签: php jquery ajax codeigniter

我正在尝试使用PHP Codeigniter中的jQuery Ajax提交表单。但似乎不起作用。我做错了...

这是HTML标记。

<form action="" method="post" enctype="multipart/form-data" class="form-horizontal">
    <!-- other form inputs ommitted -->
    <div class="col-md-3">
        <div class="box box-danger box-solid">
            <div class="box-header"> <label>User Photo </label> </div>
            <div class="box-body box-profile">
                <center>
                    <img id="user_photo_change" class="img-responsive" src="//placehold.it/400x400" alt="Profile Picture" style="max-width: 120px;">
                    <br>
                    <input type="file" name="photo" onchange="readPicture(this);">
                </center>
            </div>
        </div>
    </div>
    <div class="col-md-12">
        <center>
            <button type="reset" class="btn btn-sm bg-red">Reset</button>
            <button type="submit" id="submit" class="btn btn-sm bg-green">Save</button>
        </center>
    </div>
</form>

这是Ajax调用

<script>
    $(function() {

        $('form').on('submit', function (e) {
          e.preventDefault();

          $.ajax({
            type: 'post',
            url: '<?php echo base_url('admin/save'); ?>',
            data: $('form').serialize(),
            success: function (data) {

                $('#message').html(data);
            }
          });

        });

    });
</script>

2 个答案:

答案 0 :(得分:0)

您可以将“提交”按钮更改为普通按钮。并听其点击。希望对您有帮助。

答案 1 :(得分:0)

尝试:

$('body').on('submit','form',function(e) {
e.preventDefault();
$.ajax({ type: 'post',
 url: '',
 data: $('form').serialize(),
 success: function (data) {
   $('#message').html(data); 
   alert(data);
 }
});
});
相关问题