在 jQuery 函数之外获取 JSON 响应变量?

发布于 2025-01-05 20:17:54 字数 544 浏览 1 评论 0原文

我有以下 jQuery 函数:

function deleteHype(){
    FB.api('/me/launchhype:hype', function(response) {
            $.each(response.data, function(i, obj){
                    if (obj.data.launch.url == '<?php the_permalink(); ?>') {
                            var delete_launch_id = parentObj=obj.id;
                    }
            });
    });
}
alert(delete_launch_id);

假设在 IF 语句中 var“delete_launch_id”是“X”。好吧,如果我尝试在函数之外执行警报“delete_launch_id”,它是“未定义”的。我希望它返回“X”(假设的设置值)。

我该怎么做?我迷路了,似乎找不到类似的例子。

I have the following jQuery function:

function deleteHype(){
    FB.api('/me/launchhype:hype', function(response) {
            $.each(response.data, function(i, obj){
                    if (obj.data.launch.url == '<?php the_permalink(); ?>') {
                            var delete_launch_id = parentObj=obj.id;
                    }
            });
    });
}
alert(delete_launch_id);

Lets say in the IF statement the var "delete_launch_id" is "X". Well if I try to do the alert "delete_launch_id" outside the function it is "undefined". I want it to give me back "X" (the hypothetically value that was set).

How can I do this? I'm lost and can't seem to find a similar example.

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

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

发布评论

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

评论(4

一场信仰旅途 2025-01-12 20:17:54

根据大众的需求,这里更深入地了解了为什么变量“delete_launch_id”在“alert”函数访问它时不可用。

有几件事正在发生。

首先,FB.api 函数很可能是异步 AJAX 调用。 JavaScript 还不是真正的异步,但在这种情况下,它实际上是异步的。这意味着当异步代码执行时,后面的代码将继续执行,同时异步代码等待响应。因此,如果您调用“deleteHype”,然后立即调用“alert”,则很有可能在调用“alert”时 FB.api 响应尚未返回。因此,该异步代码中设置的任何内容都将不可用。

第二个问题是 JavaScript 具有“功能范围”。实际上,这意味着函数内部定义的变量仅在该函数内部可用。它仅在该函数内具有“范围”。考虑以下代码:

var foo = 1;
if(1 === 1) {
    // non-function block. foo is accessible in here, and any changes to foo will be seen outside this block.
    foo = 2;
}
// foo is 2

function change() {
    // functional scope. variables defined in here are only available here
    foo = 3;
    var bar = 1;
}

// foo is 2 because we haven't called change yet
// bar is "undefined"

change();

// foo is 3
// bar is "undefined"

“foo”发生了变化,因为它的作用域位于函数之外,因此函数可以访问它。
然而,“bar”仅在该函数内具有作用域,并且不存在于其他任何地方。

在原始示例中,“delete_launch_id”实际上是在多个函数中声明的,因此它在其他地方不可用。

我的第一个答案通过将函数作为“回调”传递到“deleteType”函数中来解决这些问题,该函数仅在异步代码完成并返回时才会被调用。这解决了问题#1。然后回调函数将“delete_launch_id”传递给它,这使其可用。我给出的格式可能看起来有点奇怪:

deleteHype(function(delete_launch_id) {
    // alert
});

这里发生的是我们实际上将函数作为变量传递。这是一个“匿名”函数(没有名称)。所以deleteType对待就像一个变量(因为它是),并且可以调用它,因为它是一个函数,并且当它被调用时它里面的代码就会执行。这是一个非常方便的模式。

我希望这会有所帮助。一开始这是令人困惑的事情。

By popular demand, here's a more in depth look at why the variable "delete_launch_id" isn't available at the point where it's accessed by the "alert" function.

There's a couple things going on.

First, the FB.api function is most likely an asynchronous AJAX call. JavaScript isn't truly asynchronous (yet), but in this case, it effectively behaves so. What that means is that when asynchronous code executes, code after it will continue executing while the async code waits for a response. So, there's a good chance that if you call "deleteHype", and then "alert" immediately following it, FB.api response won't have returned by the time "alert" is called. And as such, anything set within that async code won't be available yet.

The second issue is that JavaScript has "functional scope." What that means, in practice, is that a variable defined inside a function is only available inside that function. It only has "scope" within that function. Consider the following code:

var foo = 1;
if(1 === 1) {
    // non-function block. foo is accessible in here, and any changes to foo will be seen outside this block.
    foo = 2;
}
// foo is 2

function change() {
    // functional scope. variables defined in here are only available here
    foo = 3;
    var bar = 1;
}

// foo is 2 because we haven't called change yet
// bar is "undefined"

change();

// foo is 3
// bar is "undefined"

"foo" changed because it had scope outside the function, so the function can access it.
"bar" however, only has scope inside that function and doesn't exist anywhere else.

In the original example, "delete_launch_id" is declared inside several functions, actually, so it is not available anywhere else.

My first answer addresses these issues by passing a function into the "deleteType" function as a "callback" that will be called only when the async code is finished and returns. That handles issue #1. The callback function then has "delete_launch_id" passed to it, which makes it available. The format I gave may seem a little weird:

deleteHype(function(delete_launch_id) {
    // alert
});

What's going on here is that we're actually passing a function as a variable. It's an "anonymous" function (no name). So deleteType treats is like a variable (because it is), and can call it, because it's a function, and the code inside it will execute when it's called. It's a really handy pattern.

I hope that helps a bit. This is confusing stuff at first.

甜是你 2025-01-12 20:17:54

将变量声明为全局变量(或在您需要的任何地方都可以访问的命名空间中)。

问题是,一旦你这样做了,你需要担心它什么时候被访问,以及那个时候访问它是否合理。更好的解决方案取决于您实际想要做什么。

然而,一般来说,最好将这种异步内容保留在本地,并使用函数来操纵回调中的状态。例如,您可以将一个函数传递给 deleteHype,该函数使用 ID 执行“正确”的操作,在回调中执行工作,通过回调或传递给它的函数操作 DOM,等等。

Declare the variable as a global (or in a namespace accessible wherever you need it).

The problem is that once you do that, you need to worry about when it is accessed, and whether or not it is reasonable to access it at that time. Better solutions depend on what you're actually trying to do.

In general, however, it's best to keep that kind of asynch stuff local, and use functions to manipulate state within the callback. For example, you could pass a function to deleteHype that did the "right" thing with the ID, do the work within the callback, manipulate the DOM from either the callback or a function passed to it, etc.

时光暖心i 2025-01-12 20:17:54

我不会详细解释为什么您在代码中此时无法“看到”delete_launch_id 的所有原因,但也许这样的方法会起作用?:

function deleteHype(callback){
    FB.api('/me/launchhype:hype', function(response) {
            $.each(response.data, function(i, obj){
                    if (obj.data.launch.url == '<?php the_permalink(); ?>') {
                            if(typeof callback === 'function') {
                               callback(obj.id);
                            }
                    }
            });
    });
}

deleteHype(function(delete_launch_id) {
    alert(delete_launch_id);
});

I won't get into all the reasons why you can't "see" delete_launch_id at that point in the code, but maybe something like this would work?:

function deleteHype(callback){
    FB.api('/me/launchhype:hype', function(response) {
            $.each(response.data, function(i, obj){
                    if (obj.data.launch.url == '<?php the_permalink(); ?>') {
                            if(typeof callback === 'function') {
                               callback(obj.id);
                            }
                    }
            });
    });
}

deleteHype(function(delete_launch_id) {
    alert(delete_launch_id);
});
浊酒尽余欢 2025-01-12 20:17:54

您需要做的是将变量作为参数在两个函数之间传递。

function deleteHype(){
  FB.api('/me/launchhype:hype', function(response) {
    $.each(response.data, function(i, obj){
      if (obj.data.launch.url == '<?php the_permalink(); ?>') {
        var delete_launch_id = parentObj=obj.id;
      }
    });
  });
}
function grabID(delete_launch_id){
  alert(delete_launch_id);
}

你的第一个函数是完全正确的。现在你只需要第二个函数来获取参数并输出它;像下面这样。

function grabID(delete_launch_id){
  alert(delete_launch_id);
}

现在您可以在需要输出delete_launch_id的地方使用grabId。

What you need to do is pass the variable as a parameter between two functions.

function deleteHype(){
  FB.api('/me/launchhype:hype', function(response) {
    $.each(response.data, function(i, obj){
      if (obj.data.launch.url == '<?php the_permalink(); ?>') {
        var delete_launch_id = parentObj=obj.id;
      }
    });
  });
}
function grabID(delete_launch_id){
  alert(delete_launch_id);
}

Your first function is completely correct. Now you just need a second function to grab the parameter, and output it; like below.

function grabID(delete_launch_id){
  alert(delete_launch_id);
}

Now you can use grabId where you need to output the delete_launch_id.

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