如何为表单提交事件创建回调(没有ajax)

Kev*_*eal 4 javascript forms jquery amazon-s3 cross-domain

我希望在成功提交表单后进行回调.这种形式并没有重新加载页面,Ajax的选择是因为"跨出身"问题而无法提供给我们.

我现在拥有的是:

$('#uploadform form').on('submit', function(){
    // DO STUFF HERE
});
Run Code Online (Sandbox Code Playgroud)

但是一旦触发提交事件而不是回调,这就会触发.如果不使用AJAX,如何让我的代码运行,只有接收到响应(并获得做的东西与响应)之后?这甚至可能吗?

它是通过AWS的S3文件托管而不能使用JSONP.

如果我不是为了简单起见,我宁愿不使用iframe.

编辑 它不会像文件下载链接重新加载页面一样重新加载页面.否则它就像任何其他形式一样.它不是在iframe中提交的.这是一个普通的表单,但涉及的标题不需要页面重新加载.

Kev*_*eal 5

我已经找到了一个解决方案,它允许我在不重新加载页面的情况下提交表单,不使用iframe或JSONP,虽然它在技术上可能算作AJAX,但它没有相同的"交叉起源"问题.

function uploadFile() {

    var file = document.getElementById('file').files[0];
    var fd = new FormData();

    fd.append('key', "${filename}");
    fd.append("file",file);

    xhr = new XMLHttpRequest();

    xhr.upload.addEventListener("progress", uploadProgress, false);
    xhr.addEventListener("load", uploadComplete, false);
    xhr.addEventListener("error", uploadFailed, false);
    xhr.addEventListener("abort", uploadCanceled, false);

    xhr.open('POST', 'http://fake-bucket-name.s3-us-west-1.amazonaws.com/', true); //MUST BE LAST LINE BEFORE YOU SEND 

    xhr.send(fd);
}

function uploadProgress(evt) {
    if (evt.lengthComputable) {
      var percentComplete = Math.round(evt.loaded * 100 / evt.total);
      document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
    }
    else {
      document.getElementById('progressNumber').innerHTML = 'unable to compute';
    }
}

function uploadComplete(evt) {
    /* This event is raised when the server send back a response */
    alert("Done - " + evt.target.responseText );
}

function uploadFailed(evt) {
    alert("There was an error attempting to upload the file." + evt);
}

function uploadCanceled(evt) {
    alert("The upload has been canceled by the user or the browser dropped the connection.");
}
Run Code Online (Sandbox Code Playgroud)

使用这样的简单形式:

<form id="form1" enctype="multipart/form-data" method="post">
    <div class="row">
      <label for="file">Select a File to Upload</label><br>
      <input type="file" name="file" id="file">
    </div>
    <div id="fileName"></div>
    <div id="fileSize"></div>
    <div id="fileType"></div>
    <div class="row">
      <input type="button" onclick="uploadFile()" value="Upload">
    </div>
    <div id="progressNumber"></div>
</form>
Run Code Online (Sandbox Code Playgroud)

uploadComplete(evt)函数是回调函数.如您所见,它还为您提供了可以向用户显示的完整百分比.

注意:要执行此操作,您必须在S3帐户中设置正确的上载策略和CORS策略. - RonSper

  • 注意:要执行此操作,您必须在S3帐户中设置正确的上载策略和CORS策略. (2认同)