所以我选择使用全局变量,为什么这段代码会返回“未定义”警报?

发布于 2024-11-29 02:20:53 字数 471 浏览 1 评论 0原文

我想要的是从一个函数检索的数据显示在另一个函数中。有人告诉我,使用全局变量可以让我完成此任务 存储值以便在以后的函数中使用的最佳方法是什么?我听说全局变量很邪恶

这是我尝试过的。 http://jsfiddle.net/8j947/17/

当我尝试将全局变量显示为它返回为未定义的警报(在 jsfiddle 上可能无法查看)。我想这是因为数据实际上并没有被存储,但我只编码了 3 周,所以我知道什么。如果你们可以通过向我展示我做错了什么或提出替代解决方案来帮助我,那就太好了。

What I want is for data retrieved from one function to be displayed in another . I was told that using a global variable would allow me to accomplish this What is the best way to store a value for use in a later function? I'm hearing global variables are evil.

Here is what I tried. http://jsfiddle.net/8j947/17/

When I try to display the global variable as an alert it comes back as undefined (which might not be viewable on jsfiddle). I'm thinking this is because the data isn't actually getting stored, but I've only been coding for 3 weeks, so what do I know. If you guys could help me out by showing me what I did wrong or proposing an alternate solution that would be great.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅忆流年 2024-12-06 02:20:53

底部的警报函数将在调用 getCrossDomainJson 之后、调用传入 getCrossDomainJson 的回调函数之前立即执行。由于 someProperty 属性是在回调函数内设置的,因此当您在警报中引用它时,它实际上尚未设置。

为您的警报函数命名,并在回调函数完成后在其他地方调用它。

function getCrossDomainJson(url, callback) {
    $.ajax({
        url: "http://query.yahooapis.com/v1/public/yql?callback=?",
        data: {
            q: 'select * from xml where url="' + url + '"',
            format: "json"
        },
        dataType: "jsonp",
        success: callback
    });
}

var MyStatus = {};
getCrossDomainJson("http://xdiscgolfplanetx.channel-api.livestream-api.com/2.0/getstream", function(data) {
    // data is in JSON format:
    console.dir(data);
    if (data && data.query && data.query.results && data.query.results.channel) {
        var isLive = (data.query.results.channel.isLive);
        MyStatus.someProperty = data.query.results.channel.isLive;
    // alert (isLive)
        if (isLive == 'true') {
            alert ('working')
        }
        alertSomeProperty();            // now that the someProperty property has been set and MyStatus 
                                        //is global, you'll see that you can refer to it even outside of this block
    }
});

function alertSomeProperty(){
    alert (MyStatus.someProperty)
}

Your alert function at the bottom is executing immediately after getCrossDomainJson is called, and before the callback function passed into getCrossDomainJson is called. Since the someProperty property is set inside the callback function, when you refer to it in the alert, it hasn't actually been set yet.

Give your alert function a name and call it somewhere else AFTER the callback function completes.

function getCrossDomainJson(url, callback) {
    $.ajax({
        url: "http://query.yahooapis.com/v1/public/yql?callback=?",
        data: {
            q: 'select * from xml where url="' + url + '"',
            format: "json"
        },
        dataType: "jsonp",
        success: callback
    });
}

var MyStatus = {};
getCrossDomainJson("http://xdiscgolfplanetx.channel-api.livestream-api.com/2.0/getstream", function(data) {
    // data is in JSON format:
    console.dir(data);
    if (data && data.query && data.query.results && data.query.results.channel) {
        var isLive = (data.query.results.channel.isLive);
        MyStatus.someProperty = data.query.results.channel.isLive;
    // alert (isLive)
        if (isLive == 'true') {
            alert ('working')
        }
        alertSomeProperty();            // now that the someProperty property has been set and MyStatus 
                                        //is global, you'll see that you can refer to it even outside of this block
    }
});

function alertSomeProperty(){
    alert (MyStatus.someProperty)
}
断舍离 2024-12-06 02:20:53

这是使用异步编程时的一个典型错误。您不能再考虑单一的逐步执行顺序,先调用函数 a(),然后调用 b(),然后调用 c()。当使用任何形式的 ajax 调用时,它通常是异步的。这意味着调用该函数只会启动它的执行。

然后它将在后台运行,其余的 JavaScript 将继续运行并完成。然后,稍后,ajax 调用将完成并调用其成功函数。只有从该 success 函数或从 success 函数调用的任何其他代码中,您才能实际使用 ajax 调用的结果。因此,您本质上要做的就是启动 ajax 调用,然后您的 javascript 代码暂时完成。然后,您编写一个 success 函数,该函数将在 ajax 调用完成时执行您需要执行的其余操作。此时,您就拥有了 JSON 数据,并且可以用它做您想做的事情。您可以获取该数据并调用其他函数,将其传递给它们,以便它们可以对其进行操作。

因此,从成功处理程序开始执行第二步。无论您需要对检索到的数据执行什么操作,都应该从成功处理程序开始。

因此,如果您想要执行的执行流程是这样的:

a();
b();
getJSONdata();
c();
d();

您必须像这样构造它:

a();
b();
getJSONdata("xxx", function(data) {
    c(data);
    d();
})

function c(myData) {
    // do something with the passed in data
}

其中 c() 和 d() 发生在检索 JSON 数据的 success 函数中,并且仅在数据之后调用它们可用。

This is a classic mistake when using asynchronous programming. You can no longer think of a single stepwise order of execution, call function a(), then b(), then c(). When using any form of ajax call, it is usually asynchronous. That means that calling the function only starts it's execution.

It will then run in the background and the rest of your javascript will keep running and finish. Then, sometime later, the ajax call will complete and it will call it's success function. ONLY from that success function or any other code that you call from the success function can you actually use the results of your ajax call. So, what you essentially have to do is start the ajax call and then your javascript code finishes for the moment. You then write a success function which will pick up execution of the rest of what you need to do when the ajax call completes. At that point, you have your JSON data and you can do with it what you want. You can take that data and call other functions, passing it along to them so they can operate on it.

So, kick of your second step of execution from the success handler. Whatever you need to do with the retrieved data should start in the success handler.

So, if the flow of execution you wanted to do was this:

a();
b();
getJSONdata();
c();
d();

You would have to structure it like this:

a();
b();
getJSONdata("xxx", function(data) {
    c(data);
    d();
})

function c(myData) {
    // do something with the passed in data
}

where c() and d() are happening in the success function from retrieving the JSON data and they are called ONLY after the data is available.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文