Parsing an XML file with jQuery from within a class
I'm trying to create a class that receives a URL to an XML file. It needs to then parse the XML file and save the data within member variables. Here's a stripped down test version of what I'm trying to do:
function Test(filename) {
this.type = "type not set";
$(document).ready(function () {
$.ajax({
type: "GET",
url: filename,
dataType: "xml",
success: function(xmlDoc) {
var xml = $(xmlDoc)
this.type = xml.find("type").text();
}
});
});
}
If I run this function and then call document.writeLn(test.type), "type not set" is always printed out. If I write within the internal function that defines this.type to be the value from the xml, I see the value I expect.
I assume the issue has to do with the fact that the XML parsing needs to be done asynchronously from the actual function call. But, I can't co开发者_JAVA技巧me up with a way of working around that.
Any help would be appreciated. Thanks.
Your second this
refers to something else than the first this
:
Try:
function Test(filename) {
var that=this;
and then use that.type
instead of this.type
also make sure that you only access the variable after the success
callback has happened; you could write the code that uses the variable in a function and call that function from within success
.
精彩评论