4

我想在我的表单成功提交后有一个回调。此表单不会重新加载页面,并且由于“跨源”问题,我们无法使用 ajax 替代方案。

我现在拥有的是:

$('#uploadform form').on('submit', function(){
    // DO STUFF HERE
});

但这会在触发提交事件后立即触发,而不是作为回调。在不使用 ajax 的情况下,如何让代码在收到响应之后且仅在收到响应之后运行(并获取响应来处理)?这甚至可能吗?

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

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

编辑 它不会重新加载页面,就像文件下载链接不会重新加载页面一样。否则它就像任何其他形式一样。它不是在 iframe 内提交的。这是一种正常的形式,但所涉及的标题不需要重新加载页面。

4

2 回答 2

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.");
}

使用这样的简单形式:

<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>

uploadComplete(evt)作为回调的函数。如您所见,它还为您提供了可以向用户展示的完成百分比。

注意:为此,您必须在您的 S3 账户中设置正确的上传策略和 CORS 策略。– 朗斯珀

于 2012-11-02T04:51:11.673 回答
2

如果您需要访问响应,您将同样遇到 ajax 和 iframe 的“跨源”问题。

JSONP是解决“跨域”问题的唯一方法。它是托管在不同域上的所有 JSON API 所使用的,除非您尝试使用旧 IE 版本不支持的CORS 。

如果您可以控制提交表单的服务器,您应该能够使其返回与 JSONP 兼容的响应。如果没有,那你有点不走运。

于 2012-11-01T23:49:53.677 回答