我认为JavaScript没有返回值,范围和变量混乱?

时间:2014-01-27 23:10:41

标签: javascript variables scope return

我正在用JQuery调用ajax来读取一些XML并返回一些数据。我成功找到了我的文件,读了东西,并做了一些警报,成功找到了我想要的数据。我想现在将这些数据返回给调用它的函数,但不确定如何。

这是我的功能:

function getDialogParams(id, folderName) {

var dialogNode; // set variable here to open scope for return statement

$.ajax({
    type: "GET",
    url: "/" + folderName + "/dialog-params.xml",
    dataType: "xml",
    success: function (xml) {

        alert("champions!"); // runs

        $(xml).find('dialog').each(function () {

            if ($(this).find('id').text() == id) { // finds my node i want
                // runs once
                dialogNode = $(this); // seems like im declaring a new variable instead of assigning my variable i instantiated above?
                alert("width = " + dialogNode.find('width').text()); // alerts proper width
                alert("height = " + dialogNode.find('height').text()); // alerts proper height
                return;
            }

        });
    },
    error: function () { alert("fail whale!") }
});

alert("width2 = " + dialogNode.find('width').text()); // error dialogNode is undefined, wth, i declared this variable up-scope?
return dialogNode; // should be returning same object as above that alerts correct data
}

然后即时使用这个函数:

var params = getDialogParams(515, "AN0500-ASN"); // get param values

我哪里错了?这是XML,以防有人想要全部调试。

<?xml version="1.0" encoding="utf-8" ?>
<dialogs>
    <!-- SHIPMENT SCREEN -->
    <dialog>
        <id>515</id>
        <width>1000</width>
        <height>700</height>
    </dialog>
    <!-- ORDER SCREEN -->
    <dialog>
        <id>516</id>
        <width>900</width>
        <height>600</height>
    </dialog>
    <!-- CARTON SCREEN -->
    <dialog>
        <id>517</id>
        <width>800</width>
        <height>500</height>
    </dialog>
</dialogs>

1 个答案:

答案 0 :(得分:0)

好的,谢谢你们。那篇文章有帮助。以下是我的具体案例的答案,如果它可以帮助别人看到我的例子到最后。

有一些帖子提供,我不完全理解对我来说最好的解决方案的优缺点,但使用回调函数对我来说似乎是最容易理解的,并使用使用.done()的不同方法不起作用,因为它说我的对象不支持该属性或方法。

所以这是我的功能:

function getDialogParams(id, folderName, callback) {

$.ajax({
    type: "GET",
    url: "/" + folderName + "/dialog-params.xml",
    dataType: "xml",
    success: function (xml) {

        alert("champions!"); // runs

        $(xml).find('dialog').each(function () {
            if ($(this).find('id').text() == id) { // finds my node i want
                return callback($(this));
            }
        });
    },
    error: function () { alert("fail whale!") }
});
}

这就是我的称呼:

getDialogParams(515, "AN0500-ASN", function (result) {
    alert("screen width = " + result.find('width').text());
    alert("screen height = " + result.find('height').text());
});