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
jQuery "Cannot read property 'defaultView' of undefined" error
提问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 this
isn't what you were dealing with before, it's now tha ajax
jQuery object, add the context
option of $.ajax()
like this:
这是因为this
不是你之前处理的,它现在是ajax
jQuery 对象,添加这样的context
选项$.ajax()
:
$.ajax({
context: this,
url: "ajax/save_text.php",
...
This way this
inside your callbacks refers to the same this
as when you're calling $.ajax()
. Alternatively, just hold onto a reference to this
in a separate variable.
this
回调中的这种方式与this
您调用$.ajax()
. 或者,只需保留对this
单独变量的引用。
Also, you'll need to adjust $(this).value
, you probably meant this.value
or $(this).val()
.
此外,您需要调整$(this).value
,您可能是指this.value
或$(this).val()
。