views:

57

answers:

1

The problem is in the difference how browsers implement simple calls. The problem occurs while using colorbox extenstion (facebox variant). Content is loaded into colorbox with jquery load() function.

When the call is made by Chrome, Accept header is set to:

Accept: text/html, */*, text/javascript

In case of FireFox, header looks like this:

Accept: text/javascript

I tried to force the Accept header by setting it using:

jQuery.ajaxSetup({  
  'beforeSend': function (xhr) {xhr.setRequestHeader("Accept", "text/javascript")}  
}); 

It works well while using $.ajax calls, but it doesn't seem to affect .load function. Any idea how to solve this issue?

A: 

Even though it's obviously better to avoid the issue by using the $.ajax call directly, you can create a proxy method for the $.ajax method. This helps since $.load in turn calls $.ajax with a set of default parameters. We can therefore intercept $.loads call to $.ajax.

var org = $.ajax;
$.ajax = function(settings){
    settings['accepts'] = null;
    settings['beforeSend'] = function(xhr) {
        xhr.setRequestHeader("Accept", "text/javascript");
    }
    org(settings);
}

 $("#foo").load("http://fiddle.jshell.net/FpCBJ/show/light/");

Try

Obviously, this will affect ALL calls to $.ajax, so you might want to add another parameter to the proxy method which can be set and checked in the proxy to to avoid setting requestheader when called directly. Or in settings even.

I guess you could also add/remove the proxy for each call, but this adds overhead and might lead to race conditions(?) (Wouldn't think so if you remove the proxy straight after the request, don't wait for callback), so you'd need a lock of some sort.

EDIT: Added settings['accepts'] = null; to keep $.ajax from adding any headers before the callback as setRequestHeader() only adds, not replaces. Boy this is dirty.

EDIT 2: Actually, a perhaps cleaner option would be to set up your own accepts and refer to them to allow $.ajax to do its job to map the data types and set up XHR all by itself:

var org = $.ajax;
$.ajax = function(settings){
    settings['accepts'] = {"myDataType" : "text/javascript"};
    settings['dataType'] = "myDataType";
    org(settings);
}

 $("#foo").load("http://fiddle.jshell.net/FpCBJ/show/light/");
Alexander Sagen