【问题标题】:Trigger a File Upload using AJAX without a form nor Jquery使用 AJAX 触发文件上传,无需表单或 Jquery
【发布时间】:2019-12-01 01:50:50
【问题描述】:

这在以 JSON 格式获取和发送文本时效果很好。 在使用表单、输入和提交按钮上传图像时,它也能很好地工作。

function ajaxPromise(url, send) {

    return new Promise( function(resolve, reject) {

    var XHR = new XMLHttpRequest();

    XHR.open('POST', url);
    XHR.onload = function() {
      resolve(XHR.response); // Resolve promise with response
    };

    XHR.send(send);

    });
}

需要帮助才能使其在不激活提交按钮的情况下工作,例如,使用输入的更改事件。

input.addEventListener('change', function(e) {
    ajaxPromise('upload.php', file);
});

【问题讨论】:

    标签: javascript ajax file-upload promise


    【解决方案1】:

    你可以试试下面的代码

    input.addEventListener('change', function(e) {
        // this.files -- Array[Files] // when multiple files are selected.
        // so Pick the first one
        ajaxPromise('upload.php', this.files[0]);
    });
    

    【讨论】:

      猜你喜欢
      • 2012-10-05
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      • 2015-01-03
      • 2012-07-05
      • 2013-01-28
      相关资源
      最近更新 更多