/    Sign up×
Community /Pin to ProfileBookmark

Getting variable out of internal function

Hi there,

I am trying to use JavaScript to get the source of a web page, and save the source in a variable.
Problem is, the part that gets the source (responseText) is inside of a function, and so I can’t bring it out of the function because of how it works.

Here is my code:

[CODE]
function load_xml(URL) {
var xmlObj = new XMLHttpRequest();
xmlObj.open(“GET”, URL, true);
xmlObj.onreadystatechange=function() {
if (xmlObj.readyState==4) {
// This variable now contains the source
var source = xmlObj.responseText;
}
}
// Now, the variable source is empty, so I can’t return it
return source;
xmlObj.send(null);
}

var source = load_xml(“http://www.google.com”);

[/CODE]

Perhaps my comments explain the problem?

Thanks,
Jason

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@felgallJun 28.2007 — xmlObj.onreadystatechange=function() {

if (xmlObj.readyState==4) {

// This variable now contains the source

[b]return[/b] xmlObj.responseText;

}
Copy linkTweet thisAlerts:
@jason371authorJun 28.2007 — Hi,

Thanks for the reply.

That would normally work, but that returns it to the unnamed function (onreadystatechange=function()), which screws it up.

I need it returned to the main function, load_xml.
×

Success!

Help @jason371 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.10,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...