无法在进行 ajax 调用时触发成功或失败事件



我尝试使用 JQuery Ajax 调用发送发布请求,但对于我的一生,我无法触发成功或错误事件。发布请求将文件发送到后端。

我知道文件已成功上传,因为我可以在后端的日志中看到它。当我将控制台日志语句添加到成功/错误部分时,我没有得到任何排序日志记录。

这是表单的 Html。

$(document).ready(function() {
    $("#submitButton").click(function () {
        console.log("sdasd");
        console.log($("#my_file").val());
    });
    $("#reset_button").click(function () {
        $("#my_file").val("");
    });

    $('#submit_button').on('click', function() {
        $.ajax({
            // Your server script to process the upload
            url: 'http://127.0.0.1:5000/uploadTest',
            type: 'POST',
            datatype: "json",
            // Form data
            data: new FormData($('form')[0]),
            success: function( data ) {
             alert("Test Upload Successful");
           },
           error: function(xhr, status, error) {
               alert("Test Upload Successful");
           },
            // Tell jQuery not to process data or worry about content-type
            // You *must* include these options!
            cache: false,
            contentType: false,
            processData: false
        });
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" action="#" enctype="multipart/form-data">
	<!-- COMPONENT START -->
	<div class="form-group">
		<div class="input-group input-file">
			<input type="file" name="file" id="my_file">
		</div>
	</div>
	<!-- COMPONENT END -->
	<div class="form-group">
		<button id="submit_button" type="submit" class="btn btn-primary pull-right">Submit</button>
		<button type="reset" class="btn btn-danger">Reset</button>
	</div>
	<p>The test must be a .docx file in the specified format </p>
	<p id="file_upload_message"/>
</form>

<button type="submit">

将导致表单提交到服务器,并将有效地刷新页面。

<button type="button">

并且表单不会进行提交,您的 Ajax 提交将有机会通过。

最新更新