0

I am trying to apply a .js file to a page I loaded via ajax (since ajax automatically strips the content of all the javascript).

var url;
var textUrl = 'local/file.js';

$('a').click(function() {
    url = $(this).attr('href');
    $('.secondaryDiv').load(url, function() {
        $.getScript(textUrl, function(data, textStatus, jqxhr) {
        console.log(data); //data returned from getScript
        console.log(textStatus); //return "success"
        console.log(jqxhr.status); //200
        });
    });
return false;
}); 

Am I approaching this the right way? I tried everything I could think of and I can't get it to work

agassi0430
  • 1,155
  • 1
  • 13
  • 31
  • The top two answers on [this question](http://stackoverflow.com/questions/889967/jquery-load-call-doesnt-execute-javascript-in-loaded-html-file) seem to address what you're trying to achieve, if I'm reading your question right. – Kelvin Nov 11 '12 at 05:01
  • What is the browser console saying? Can you elaborate more than "can't get it to work", please? – Coby Nov 11 '12 at 05:03
  • giving me a 403 (forbidden) message – agassi0430 Nov 11 '12 at 05:07
  • For the `.load()` or for the `$.getScript()`? You need to explain in more detail instead of me having to pry the information out of you. :) – Coby Nov 11 '12 at 05:12
  • Sorry I am still new to this. The .load() works and loads the innerHTML page just fine, but the .getScript() isn't working. The error is for the .getScript – agassi0430 Nov 11 '12 at 05:17
  • Okay. Have you checked to see whether it is hitting the correct URL for **file.js** (Eg: `/wrong/local/file.js` vs. `/right/local/file.js`)? Is it located on the same domain? – Coby Nov 11 '12 at 05:23
  • The file I am pulling is hosted online through amazon web servers. Yes I checked and it is the right file – agassi0430 Nov 11 '12 at 05:25

1 Answers1

0

You can create a new <script> element and programmatically set its src attribute to point at the correct file:

var url;
var textUrl = 'local/file.js';

$(document).ready(function() {
    $('a').click(function() {
        url = $(this).attr('href');
        $('.secondaryDiv').load(url, function() {
            var s = $('<script>', {
                type: 'text/javascript'
            });
            $(this).append(s);
            s[0].src = textUrl;
        });
        return false;
    });
});​
nbrooks
  • 18,126
  • 5
  • 54
  • 66