$.ajax抛出奇怪的“Uncaught TypeError: Illegal invocation”错误

14

我有一些jQuery代码,它会抛出一个非常奇怪的错误。 Google Chrome 报告了这个错误:Uncaught TypeError: Illegal invocation 并且说它是在 jquery-1.4.4.min.js 的 144 行的 c.extend.param.e 中抛出的,但是将其回溯到我的 $.ajax 调用,代码如下:

$.ajax({
   url: target,
   type: method,
   dataType: 'json',
   data: sendData,
   success: function(result) {
       if (result.redirect) {
           window.location = result.redirect;
       }
       else {
           for (var i in result) {
                if ($(i).size()) {
                    $(i).html(result.i);
                }
            }
        }
    }
});

在SO上看到一个问题,和这个问题很像的是使用了$没有正确地将其包含在jQuery函数中,但我相当确定这次不是我的错误,因为我很小心。

2个回答

19

问题就在这里:

event.preventDefault();
var data = $.extend({
    referrer: window.location, <-- window.location is an object,
                                   should be window.location.href
    href: $(this).attr('href')
}, options.linkData);
loadPage(options.linkUrl, options.linkMethod, data);

更改此设置后,它可以正常工作,为什么会导致错误?

<jQUery1.4.4 at line 6079>
s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value)

encodeURIComponent 不支持 window.location 对象,因为它只接受 字符串

参见:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent


4
没问题 :) 只需要五分钟时间(如果你知道需要查找什么)。 - Ivo Wetzel
event.preventDefault(); var data = $.extend({ referrer: window.location, <-- window.location is an object, should be window.location.href href: $(this).attr('href') }, options.linkData); loadPage(options.linkUrl, options.linkMethod, data);这段代码是从哪里来的?提问者在问题中没有包含这段代码... - Scott Tesler
@ScottDavidTesler,jsfiddle链接已经失效(抱歉),因此已被删除。我在问题中包含了我认为导致错误的部分,但Ivo找到了正确的部分。 - Nathan MacInnes

2

谢谢,那是另一个问题。它不是抛出错误的那个,但你帮我省去了很多烦恼。 - Nathan MacInnes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接