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

时间:2010-10-14 18:14:37

标签: jquery ajax

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

代码摘录:

$.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");
    }
});

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

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

1 个答案:

答案 0 :(得分:35)

这是因为this不是你之前处理过的,现在是ajax jQuery对象,添加context option of $.ajax()就像这样:

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

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

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

相关问题