【问题标题】:Is a form necessary on .ajaxSubmit() if calling it from the file input button?如果从文件输入按钮调用 .ajaxSubmit() 是否需要表单?
【发布时间】:2015-05-18 01:54:34
【问题描述】:

我正在按照jquery form plugin 中的示例将图像异步上传到我的服务器。我只有一个按钮“添加照片”,可以按下它来选择一张照片。然后发布到我的服务器以保存图像并在缩略图库中刷新下面的图像。我这里还需要表格吗?好像我没有,因为我没有使用提交按钮,我在添加照片后提交。当我必须显示所有图像并用新图像刷新页面时,这会让我感到困惑吗?只是好奇反馈。 这是我的 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;
    //});
});

【问题讨论】:

    标签: javascript jquery file-upload ajaxform


    【解决方案1】:

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

    如果您想在不使用表单的情况下上传文件,文件系统 api 上的 hmtl5 rocks tutorial 会很有帮助。

    【讨论】:

    • 您知道在 ASP MVC 中是否有使用此功能并将数据传递给控制器​​的示例?
    猜你喜欢
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 2021-07-13
    • 2017-11-21
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    相关资源
    最近更新 更多