jQuery和QUOT;不能读取属性“默认视图”中未定义"错误视图、属性、中未、定义

2023-09-10 17:13:49 作者:东风寄千愁

我使用jQuery来发布表单域取决于它的工作,或者只是简单地返回1/0 PHP文件不...

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...

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

不过,每次它是成功的(HTML == 1)控制台抛出了这个错误吗?未捕获的类型错误:无法读取属性默认视图未定义,并警告从未发生过...

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...?

谷歌似乎并没有对这个错误和jQuery,谁知道原因很多信息?

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

推荐答案

这是因为是不是你正在处理之前,它现在塔 AJAX jQuery对象,加上 上下文 $选项阿贾克斯() 这样的:

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:

$.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.

此外,你需要调整 $(这).value的,你可能是指 THIS.VALUE $(本).VAL()

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