gpt4 book ai didi

javascript - Ajax 和范围问题

转载 作者:行者123 更新时间:2023-11-28 15:46:05 25 4
gpt4 key购买 nike

我在 AJAX 和数据范围方面遇到了一些问题。我是 Javascript 新手,我不知道如何解决我的问题。

  var urlList = new Array();
$.ajax({
url: "http://localhost:3000/url",
success: function(data) {
alert(data.expressions.url); //This shows the correct result
urlList[0] = obj.expressions.dom;
}
});

alert(urlList[0]); //this shows undefined

我需要 urlList[0] 中的数据,以便稍后使用它。我认为这是一个范围问题。

有人能给我指出正确的方向吗?

谢谢

最佳答案

这不是范围问题,而是时间问题。 ajax方法是异步执行的。这意味着调用它不会导致您的程序等待它完成。这会导致在请求完成之前显示警报。

要解决此问题,请将请求也放入成功函数中。这是处理请求结果的正确位置。

var urlList = new Array();

$.ajax({
url: "http://localhost:3000/url",
success: function(data) {

alert(data.expressions.url); //This shows the correct result

urlList[0] = obj.expressions.dom;

// This might work now, depending on what `obj.expressions.dom` is. This
// isn't becoming clear from your code. Usually you would use the `data`
// parameter of the success function, which contains the response body of
// the ajax request that has just finished.
alert(urlList[0]);

// of course you can call other functions as well. For instance, you
// could call
urlListChanged();
// ..which you can declare in global scope. This way, you can repond to
// changes from multiple sources, without having to duplicate code.
// It will all work, as long as you use the success handler as the trigger.
}
});


function urlListChanged()
{
alert(urlList[0]);
}

关于javascript - Ajax 和范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22211042/

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