gpt4 book ai didi

javascript - jQuery/JavaScript 变量作用域

转载 作者:搜寻专家 更新时间:2023-11-01 05:26:30 24 4
gpt4 key购买 nike

 var field1;
var field2;
function setUserFields() {
$.ajax({
type: "POST",
url: "url",
dataType: "xml",
complete: parseXml
});
}
function parseXml {
$(xml.responseXML).find("myValue").each(function()
{
field1 = $(this).attr('attr1');
field2 = $(this).attr('attr2');
alert(field1 + ' ' field2); //shows correct values
});
}
setUserFields();

$(function() {
alert(field1); //undefined in IE and Chrome | Gives correct value in FireFox
alert(field2); //undefined in IE and Chrome | Gives correct value in FireFox
})

我没有发布我正在运行的确切代码,因为代码相当复杂。如果发布的代码中存在语法错误,请忽略它们,因为这些不是导致我出现问题的原因。该代码在 Firefox 中按预期工作,但在 IE 或 Chrome 中不工作。此外,我可以在 Firebug lite 中验证代码运行的顺序不会导致问题。我想要做的是调用 Web 服务,解析结果并将所需的信息存储在全局变量中,以供以后只能在 DOM 加载完成后调用的函数使用。我在加载文档之前运行了 setUserFields 函数。该函数被调用并设置变量,但变量仅在 parseXML() 的范围内可用。由于我已经在所有函数的范围之外声明了变量,并且在 parseXML 函数中设置了变量,所以我希望这些变量是全局设置的。但是,只有在 firefox 中我才能访问变量而不定义它们。我是 javascript 领域的新手,所以我可能错过了一个明显的陷阱。我尝试谷歌搜索几个小时但没有任何运气。任何帮助将不胜感激。

最佳答案

这不是范围问题。这可能是由于 AJAX 调用的异步性质。

The first letter in Ajax stands for "asynchronous," meaning that the operation occurs in parallel and the order of completion is not guaranteed. The async option to $.ajax() defaults to true, indicating that code execution can continue after the request is made. Setting this option to false (and thus making the call no longer asynchronous) is strongly discouraged, as it can cause the browser to become unresponsive.

jQuery.ajax()

关于javascript - jQuery/JavaScript 变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4457098/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com