How to use xml response as XMLObject outside of ajax callback function
Hopefully I've just made a dumb oversight, but I can't figure out why the following doesn't work:
$(function() {
var xml;
$.get(
"somexml.xml",
function(data){
xml = data;
},
"xml");
alert(xml);
});
If I put the alert开发者_JS百科 inside of the callback function, I get back object XMLdocument
but if I place it outside of the ajax call, I get undefined
.
Since my goal is to have a new DOM to parse, I don't want the entire handling of the XMLdocument to be within the callback function.
I've tried defining the variable outside of the entire onready function, inside at the top (like above) and inside the callback function, all with no luck.
According to Specifying the Data Type for Ajax Requests in the jquery documentation, this should be possible.
AJAX is defined as Asynchronous JavaScript and XML -- although people use the term for synchronous and non-XML requests too. Nevertheless, asynchronous means that the request will execute on a separate thread. xml
is undefined because the following is happening:
Request is sent ->
xml
var is accessed -> response is received ->data
is assigned toxml
variable
As you can see, the data received back isn't assigned to the xml
var until after you tried to access it. If you just want a separate block for handling the XML data, why not create a separate function and pass it as a parameter?
$(function() {
$.get(
"ews_cal_finditem.xml",
parseXML,
"xml");
});
function parseXML(data) {
// This is the callback function
alert(data);
}
Or even
$(function() {
$.get(
"ews_cal_finditem.xml",
function(data){
parseXML(data);
},
"xml");
});
function parseXML(xml) {
alert(xml);
}
You could also run the ajax call as async=false, but this should be done carefully as it will block further execution until it's complete. You have to be careful when you take the A out of AJAX.
精彩评论