jQuery“无法读取未定义的属性'defaultView'”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3936211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:22:36  来源:igfitidea点击:

jQuery "Cannot read property 'defaultView' of undefined" error

jqueryajax

提问by Pez Cuckow

I am using jQuery to post a form field to a PHP file that simply returns 1/0 depending on whether it worked or not...

我正在使用 jQuery 将表单字段发布到一个 PHP 文件中,该文件只返回 1/0,具体取决于它是否有效......

Extract of the code:

代码摘录:

$.ajax({
    url: "ajax/save_text.php", //Relative?!?
    //PHP Script
    type: "POST",
    //Use post
    data: 'test=' + $(this).val(),
    datatype: 'text',
    //Pass value       
    cache: false,
    //Do not cache the page
    success: function(html) {
        if (html == 1) {
            $(this).hide().siblings('span').html($(this).value).show();
                    alert("awesome!");
        } else alert('It didn\'t work!');
    },
    //Error
    error: function() {
        alert("Another type of error");
    }
});

However everytime it is successful (html == 1) the console throws up the error "Uncaught TypeError: Cannot read property 'defaultView' of undefined" and the alert never happens...?

然而,每次成功(html == 1)时,控制台都会抛出错误“Uncaught TypeError:无法读取未定义的属性'defaultView'”并且警报永远不会发生......?

Google doesn't seem to have much info on this error and jQuery, who knows the cause?

Google 似乎没有太多关于此错误和 jQuery 的信息,谁知道原因?

回答by Nick Craver

It's because thisisn't what you were dealing with before, it's now tha ajaxjQuery object, add the contextoption of $.ajax()like this:

这是因为this不是你之前处理的,它现在是ajaxjQuery 对象,添加这样的context选项$.ajax()

$.ajax({
  context: this,
  url: "ajax/save_text.php",
  ...

This way thisinside your callbacks refers to the same thisas when you're calling $.ajax(). Alternatively, just hold onto a reference to thisin a separate variable.

this回调中的这种方式与this您调用$.ajax(). 或者,只需保留对this单独变量的引用。

Also, you'll need to adjust $(this).value, you probably meant this.valueor $(this).val().

此外,您需要调整$(this).value,您可能是指this.value$(this).val()