Its because of the asynchronous nature of javascript. You have to wait for the data to come back before you can use it. You would need to do something like this:
function url_content(url){
return $.get(url);
}
url_content("local_templates/template1.html").success(function(data){
alert(data);
});
or just
$.get("local_templates/template1.html").success(function(data){
alert(data);
doSomeStuffWithTheResult(data);
});
function doSomeStuffWithTheResult(content) {
// code that depends on content goes here...
}
If you absolutely must keep in synchronous you can do this(NOT RECOMMENDED)
function getRemote(remote_url) {
return $.ajax({
type: "GET",
url: remote_url,
async: false
}).responseText;
}
jQuery: Performing synchronous AJAX requests
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…