jQuery ajax Uncatch TypeError: 非法调用

jQuery ajax Uncaught TypeError: Illegal invocation

本文关键字:非法 调用 TypeError ajax Uncatch jQuery      更新时间:2023-09-26

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

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

代码如下:

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())函数需要在window对象的"上下文"中调用。

当你执行success: alert时,jQuery在运行AJAX请求的jqXHR对象的contect中调用成功回调。 像这样:

success.call(jqXHR, data)

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

因此,您的alert在错误的"上下文"中被调用,因此它抛出了一个错误。 要修复它,只需将一个匿名函数传递给success

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

或者,如果您确实愿意,可以使用.bind()来确保在正确的上下文中调用alert()

success: alert.bind(window)

如果你真的想保留success: alert,那么你可以通过在$.ajax调用中添加context: window来告诉jQuery在正确的上下文中调用它。

请注意,alert.bind()(反过来context: window)可能不适用于所有浏览器,因此建议使用。 我建议您使用如图所示的匿名函数。