Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am reading content of a local file using jquery and I get undefined.

I feel the problem is related to synchronization of URL loading. But I don't have any idea about how to fix this code:

function url_content(url)
{
    var content;
    $.get(url,function( data ) {content=data});
    return content;
}


var content=url_content("local_templates/template1.html");
alert(content);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
301 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...