繁体   English   中英

XMLHttpRequest到jQuery Ajax

[英]XMLHttpRequest to jQuery Ajax

我有这段代码,我想要使用jQuery Ajax。

var input = document.getElementsByTagName("input")[0], file, target, i, len;
input.addEventListener("change", function(e) {
    target = e.target.files;

    for (i = 0, len = target.length; i < len; i += 1) {
        file = target[i];
    }
    var fd = new FormData();
    fd.append('image', file);
    console.log(fd);


    var xhttp = new XMLHttpRequest();
    xhttp.open('POST', "https://api.imgur.com/3/image", true);
    xhttp.setRequestHeader('Authorization', 'Client-ID xxxxxxxxxxxxxxx');
    xhttp.onreadystatechange = function () {
        if (this.readyState === 4) {
            if (this.status >= 200 && this.status < 300) {
                var response = '';
                try {
                    response = JSON.parse(this.responseText);
                } catch (err) {
                    response = this.responseText;
                }
                console.log(response);
            } else {
                throw new Error(this.status + " - " + this.statusText);
            }
        }
    };
    xhttp.send(fd);
    xhttp = null;
});

我已经尝试过使自己动手,但没有成功。

我尝试过的代码:

$.ajax({
      url: "https://api.imgur.com/3/image",
      method: "POST",
      headers: {
            'Authorization':'Client-ID xxxxxxxxxxxxxxx'
      },
      data: fd,
      success: function(response) {
            console.log(response);
      }
});

但是记录错误:

未捕获的TypeError:非法调用

如果删除data: fd ,它可以正常工作data: fd ,但是需要数据。

$.ajax({
    url: 'https://api.imgur.com/3/image',
    method: 'POST',
    data: fd,
    processData: false,
    headers: { 'Authorization': 'Client-ID xxxxxxxxxxxxxxx' },
    success: function(data){
        //do your parsing here
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM