Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

javascript - 在不使用表单或Jquery的情况下使用AJAX触发文件上传(Trigger a File Upload using AJAX without a form nor Jquery)

this works well when Getting and Sending text in JSON format.

(当以JSON格式获取和发送文本时,此方法效果很好。)

It also works well when uploading images using a form an input and a submit button.

(当使用表单输入和提交按钮上传图像时,它也很好用。)

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

    });
}

Need help in making it work without activating the submit button, for example, with the change event of the input.

(需要帮助,以使其在不激活提交按钮的情况下工作,例如,使用输入的change事件。)

input.addEventListener('change', function(e) {
    ajaxPromise('upload.php', file);
});
  ask by 10Y01 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Can you try the below code

(你可以尝试下面的代码吗)

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]);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...