1

I'm trying to load a script file via $.ajax and also set some headers in the request, is this possible? It seems to work in chrome but not firefox, the file loads and I can see it in the scripts tab of firebug but in the callback when I try to use the script I get an error.

If I remove the headers from the request then it works fine. but I need to have the headers added to the request.

I'm not using $.getScript as it does not allow headers to be set.

I would like form thing like this:

$.ajax({
   url: '/somefile',
   contentType: 'application/javascript',
   headers: { someheader: 'somevalue'},
   type: 'get',
   success: function(data){ 
       eval(data);  // dont seem to need this in chrome
       doSomethingWithNewScript();
   }
});

Update the error is not an error with making the request. I get 'doSomethingWithNewScript' not defined when I try and use the script. so its as if the request is fine but firefox cant use the script.

The headers set are custom headers like 'X-Username': 'dave'

Dave
  • 3,812
  • 5
  • 31
  • 39
  • which error you are getting when you set headers? also, what you are setting as headers? – Hardik Patel Mar 21 '12 at 16:17
  • Hi Hardik, please see my update, cheers. – Dave Mar 21 '12 at 16:27
  • 1
    http://stackoverflow.com/questions/1199676/can-i-create-script-tag-by-jquery – ZiTAL Mar 21 '12 at 16:31
  • Hi ZiTAL this solution workd for me, if you post it as an answer i can give you the points. Its also worth nothing that this lead me to finding a structual problem with my code, which didnt cause an error and passed all my test but when loaded with ajax prevented the browser from recognising the javascript - only when headers were added to the request. – Dave Mar 23 '12 at 11:39

1 Answers1

1

Try specifying dataType when you make the request, so that jQuery will handle the response as you are expecting:

...
type: 'get',
dataType: 'script',
...
rfunduk
  • 30,053
  • 5
  • 59
  • 54