gpt4 book ai didi

javascript - XMLHttpRequest 到 jQuery Ajax

转载 作者:行者123 更新时间:2023-12-03 01:13:20 25 4
gpt4 key购买 nike

我有这段代码,我希望它使用 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);
}
});

但记录错误:

Uncaught TypeError: Illegal invocation

如果我删除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
}
});

关于javascript - XMLHttpRequest 到 jQuery Ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52127281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com