gpt4 book ai didi

javascript - jQuery ajax 未捕获类型错误 : Illegal invocation

转载 作者:行者123 更新时间:2023-11-28 19:26:25 25 4
gpt4 key购买 nike

我读过的关于这个问题的所有帖子都是因为传递的对象包含其他对象,而不是原始值。

我的数据对象都是原始值,但它仍然不起作用。

代码如下:

function ImageUploader(imgEl, params) {
this.imgEl = imgEl;
this.params = params;
this.params["Function"] = "saveImage";
}

// send data from asynchronously uploaded image (as image URI)
// to PHP script which will write data to file
ImageUploader.prototype.uploadImage = function () {
var iu = this;
var fileReader = new FileReader();

fileReader.onload = function (e) {
iu.params["Image"] = e.target.result;
console.log(iu.params);
$.ajax({
type: "POST",
url: "/scripts/php/Form.php",
data: iu.params,
success: alert,
error: function (jqXHR, status, error) {
console.log(error, this);
}
});
};

this.params["FileName"] = this.imgEl.files[0].fileName || this.imgEl.files[0].name;
fileReader.readAsDataURL(this.imgEl.files[0]);
};

这是一个它拒绝的示例对象:

{
FileName: "Matrix.jpg",
Function: "saveImage",
ID: 10,
Image: "data:image/jpeg;base64,...",
Line: 1,
Name: "Test Form"
}

最佳答案

此错误与您的 iu.params 对象无关。错误在于这一行:

success: alert,

需要在窗口的“上下文”中调用window.alert()(或只是alert())函数对象。

当您执行success:alert时,jQuery 会在运行 AJAX 请求的 jqXHR 对象的上下文中调用成功回调。像这样的事情:

success.call(jqXHR, data)

我不知道 jQuery 使用的确切代码

因此,您的 alert 是在错误的“上下文”中调用的,因此会引发错误。要修复此问题,只需将匿名函数传递给 success:

success: function(data){
alert(data);
}

或者,如果您确实想要,您可以使用.bind()来确保在右侧调用alert()上下文:

success: alert.bind(window)

如果您真的 真的想要保持成功:警报,那么您可以告诉 jQuery 在正确的上下文中调用它,方法是添加context: window 到您的 $.ajax 调用。

请注意,alert.bind()(以及 context: window)可能无法在所有浏览器中工作,因此不能建议。我建议您使用如图所示的匿名函数。

关于javascript - jQuery ajax 未捕获类型错误 : Illegal invocation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27801864/

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