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

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

javascript - Get URL content using jquery

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

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...