jQuery ajaxSetup beforeSend not executing in IE8

2019-02-19 04:42发布

问题:

My project uses jQuery 1.4.2. I've got some security information that I add to my AJAX headers... The way I'm doing this is by using $.ajaxSetup(), and setting a beforeSend function.

$(document).ready(function (e) {
    $.ajaxSetup({
        global: true,
        beforeSend: function (jqXHR, settings) {
            var verificationToken = 'some encrypted string';
            jqXHR.setRequestHeader("X-Request-Verification-Token", verificationToken);
        }
    });
})

As I understand it, this should then execute every time I make a call to $.ajax(), right? It works fine in Chrome, Firefox, IE9, and so on, but occasionally not in IE7/8.

Here's where I call it:

$.ajax({
    type: "POST",
    async: true,
    data: 'somedata',
    url: "/some/url",
    success: function (data) {
        alert("success");
    },
    error: function (data) {
        alert("error");
    }
});

I've found a workaround, which is to add the beforeSend directly to the $.ajax() call (below), but I really want to do this globally, rather than have to add it to loads of places in the code...

$.ajax({
    type: "POST",
    async: true,
    data: 'somedata',
    url: "/some/url",
    success: function (data) {
        alert("success");
    },
    error: function (data) {
        alert("error");
    }
    beforeSend: function (jqXHR, settings) {
        var verificationToken = 'some encrypted string';
        jqXHR.setRequestHeader("X-Request-Verification-Token", verificationToken);
    }
});

Any clues?

Thanks! Neil

回答1:

Ok, in the absence of any other answer, I hereby declare this to be a bug in JQuery 1.4.x. The solution is to upgrade to a later version of JQuery, which sadly isn't possible for me.

If anyone has any better answer/fix, I'll happily delete this one, and mark theirs as correct.