从类中解析带有jQuery的XML文件

时间:2022-12-01 11:37:42

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:

我正在尝试创建一个接收XML文件的URL的类。然后,它需要解析XML文件并将数据保存在成员变量中。这是我正在尝试做的一个精简测试版本:

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.

如果我运行此函数然后调用document.writeLn(test.type),则始终打印出“type not set”。如果我在定义this.type的内部函数中写入xml的值,我会看到我期望的值。

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 come up with a way of working around that.

我认为这个问题与XML解析需要从实际函数调用异步完成这一事实有关。但是,我无法想出办法解决这个问题。

Any help would be appreciated. Thanks.

任何帮助,将不胜感激。谢谢。

1 个解决方案

#1


1  

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

然后使用that.type而不是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.

还要确保在成功回调发生后才访问变量;你可以编写在函数中使用变量的代码,并从成功中调用该函数。

#1


1  

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

然后使用that.type而不是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.

还要确保在成功回调发生后才访问变量;你可以编写在函数中使用变量的代码,并从成功中调用该函数。