2

I have an external javascript file that I want to use to collect the contents of a number of text files. JQuery .get() seems the most obvious choice. I can make this work if the JQuery is in the page, but not when the JQuery is in the external file. I'm missing something hugely simple...and I am currently mixing normal javascript with JQuery in the same file which I fear is poor form.

All files I am trying to access are within the same file structure. Currently I have the following in my external .js:

function addPanels() { // eventually loop over list of local HTML files // and do some stuff with the results... fileContents = readHTMLFile(); } jQuery(function($){ readHTMLFile = $.get('../html/test.html', function(data) { alert('Loaded something'); return(data); }); }); 

My HTML page contains the following:

<script type="text/javascript"> $(document).ready(function(){ addPanels(); }); </script> 

Pretty sure this is a RTFM moment so direction towards the right manual/tutorial would be great!

Dan

2 Answers 2

5

The jQuery.get is a asynchronous function, with a callback that executes when the server returns the requested document. Therefore, you cannot return any data from the method.

function addPanels() { // will not work fileContents = readHTMLFile(); } ... readHTMLFile = $.get('../html/test.html', function(data) { // will not work return(data); }); 

This however, will work:

var addPanelCallback = function(html) { // append html (or something like that) alert(html); }; var addPanel = function(url) { $.get(url, addPanelCallback); }; addPanel('../html/test1.html'); addPanel('../html/test2.html'); 

Example: http://jsfiddle.net/FgyHp/

Sign up to request clarification or add additional context in comments.

Comments

4

In your script "readHTMLFile" is not known by function "addPanels", you should put them in same level.

This script should works

<script type="text/javascript"> (function($){ var readHTMLFile = function(url){ var toReturn; $.ajax({ url: url, async: false }).done(function(data){ toReturn = data; }); return toReturn; }; $.addPanels = function(url){ fileContents = readHTMLFile(url); }; })(jQuery); </script> 

And in your page you can call it like that:

<script type="text/javascript"> $(document).ready(function(){ $.addPanels('../test/test.html'); }); </script> 

1 Comment

This solution dosen't work. Go to: jsfiddle.net/3FbXu and open the console.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.