如果从文件输入按钮调用 .ajaxSubmit() 时,它是必需的表单

Is a form necessary on .ajaxSubmit() if calling it from the file input button?

本文关键字:表单 输入 文件 按钮 调用 ajaxSubmit 如果      更新时间:2023-09-26

我正在按照jquery表单插件中的示例将图像异步上传到我的服务器。我只有一个按钮,"添加照片",按下它来选择照片。然后发布到我的服务器以保存图像并在缩略图库中刷新下面的图像。我什至需要在这里填写表格吗?似乎我没有,因为我没有使用提交按钮,而是在添加照片后提交。当我必须显示所有图像并使用新图像刷新页面时,这会让我绊倒吗?只是好奇反馈。这是我的 html 表单。

<form id="imageform" enctype="multipart/form-data" >
  <input type="file" id="selectedFile" style="display: none;" />
  <input type="button" value="Add Photos" class="btn" id="pictureupload" />
</form>
<h1>Output Div (#output2):</h1>
<div id="output">AJAX response will replace this content.</div>

这是我的JavaScript。

$("#pictureupload").click(function () {
  document.getElementById('selectedFile').click();
});
$('#selectedFile').change(function() {
    var uploadImageUrl = $('#imageform').data('url');
    var options = {
        target: '#output',   // target element(s) to be updated with server response 
        beforeSubmit: showRequest,  // pre-submit callback 
        success: showResponse,  // post-submit callback 
        // other available options: 
        url:       '/ManageSpaces/UploadImage', //uploadImageUrl, //'/ManageSpaces/UploadImage',         // override for form's 'action' attribute 
        type:      'post'        // 'get' or 'post', override for form's 'method' attribute 
        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 
        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    };
    // bind to the form's submit event 
    //$('#imageform').submit(function () {
        // inside event callbacks 'this' is the DOM element so we first 
        // wrap it in a jQuery object and then invoke ajaxSubmit 
        $(this).ajaxSubmit(options);
        // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        //return false;
    //});
});

您需要表单,因为您正在使用它来发送文件,但是如果您使用文件系统 API 并自己发送文件,则可以摆脱它。

这个关于文件系统 api 的 hmtl5 岩石教程在不使用表单的情况下上传文件很有帮助。