jQuery.ajax()成功回调存储数据返回

时间:2022-10-08 07:55:38

I'm trying to get some data from a PHP script in a project right now. All examples I found searching for AJAX callback functions "use" the data already in the callback itself, but I want to fetch data and store it in a way ready to be returned.

我正试图从项目中的PHP脚本中获取一些数据。我发现搜索AJAX回调函数的所有示例都“使用”回调本身已有的数据,但我想获取数据并以准备好返回的方式存储它。

function getEle (id) {
    var element = []; 

    $.ajax({
        url: 'slides.php',
        type: 'POST',
        data: {"id": id},
        success: function(data) {
            var content = data;

            element[0] = id;
            element[1] = content;
            // if I alert(element[1]); here it will work! 



        }
    });
    alert(element[1]); // here it just won't :/ ("undefined")
    return element;
}

Somewhere in my script some function needs to getEle(ments) but all I get is undefined. is there a way to do what I want? Or is there maybe a better way to do this?

在我的脚本的某个地方,某些功能需要getEle(ments),但我得到的都是未定义的。有办法做我想要的吗?或者有没有更好的方法来做到这一点?

5 个解决方案

#1


7  

A solution would be to pass a callback function to getEle():

解决方案是将回调函数传递给getEle():

getEle(id, callback){
  $.ajax({
    /* some options, */
    success: function(){
      var content = data;
      element[0] = id;
      element[1] = content;
      callback(element);
    }
  })
}

And then pass a function containing the code of what to do when you have the element content:

然后传递一个函数,其中包含元素内容时要执行的操作的代码:

getEle('myId', function(element){
  alert(element[1]);
});

#2


2  

Two things are failing here:

这里有两件事情失败了:

  • Variable scope - You define the variable content inside the AJAX callback. This makes it inaccessible from the surrounding code. You could omit the var and just write content = data which makes it accessible globally.
  • 变量作用域 - 您可以在AJAX回调中定义变量内容。这使得它无法从周围的代码中访问。您可以省略var,只需编写content = data,这样可以全局访问。

  • Asynchronicity - Becaus AJAX is asynchronous the script following the callback will be executed before the callback was executed. The only way to solve that problem is to use the callback as it's intended to.
  • Asynchronicity - Becaus AJAX是异步的,回调后的脚本将在执行回调之前执行。解决该问题的唯一方法是按照预期使用回调。

Take a look at this.

看看这个。

function getEle (id, callback) {
        var element = []; 

        $.ajax({
            url: 'slides.php',
            type: 'POST',
            data: {"id": id},
            success: function(data) {
                var content = data;
                element[0] = id;
                element[1] = content;

                callback(element);
            }
        });
    }
}

getEle ("someID", function(someElement) {
    alert(someElement);
});

#3


1  

Here's what's happening in your code:

这是您的代码中发生的事情:

  • the array "element" is initialized.
  • 数组“element”已初始化。

  • the AJAX call is made with a success callback function
  • AJAX调用是使用成功回调函数完成的

  • while it's waiting for that AJAX to run, it goes ahead with the rest of your code and alerts element[1], which doesn't exist yet
  • 当它正在等待AJAX​​运行时,它会继续执行其余的代码和警报元素[1],但它还不存在

  • the success callback runs and populates the array "element".
  • 成功回调运行并填充数组“元素”。

You might consider a global variable to solve this:

您可以考虑使用全局变量来解决此问题:

var element = []; 

function getEle (id) {
    $.ajax({
        url: 'slides.php',
        type: 'POST',
        data: {"id": id},
        success: function(data) {
            var content = data;
            element[0] = id;      // the global "element" is set
            element[1] = content;
        }
    });
}
// element[0] will exist now, but only after the AJAX call is complete

Alternatively, you could turn your AJAX into a synchronous call:

或者,您可以将AJAX转换为同步调用:

function getEle (id) {
    var element = []; 

    $.ajax({
        async: false,   // forces synchronous call
        url: 'slides.php',
        type: 'POST',
        data: {"id": id},
        success: function(data) {
            var content = data;
            element[0] = id;
            element[1] = content;
        }
    });
    alert(element[1]); // now it is set
    return element;
}

The only other option I can see is to keep everything tied up inside the "success" callback, which you already discovered works fine.

我能看到的唯一另一个选择是将所有内容都绑定在“成功”回调中,你已经发现它可以正常工作。

#4


0  

Your callback executes some time after the rest of your code finishes.

在其余代码完成后,您的回调会执行一段时间。

You need to pass the value back using a callback, the way $.ajax does.

你需要使用回调传递值,就像$ .ajax那样。

#5


-1  

Your alert ends up being undefined because the AJAX call is asynchronous. So while that AJAX call is waiting for the server's response, the script continues on to the alert, at which point element[1] is not yet defined.

您的警报最终未定义,因为AJAX调用是异步的。因此,当AJAX调用正在等待服务器的响应时,脚本继续执行警报,此时尚未定义元素[1]。

You should place your return element line inside of the success callback function.

您应该将返回元素行放在成功回调函数中。

#1


7  

A solution would be to pass a callback function to getEle():

解决方案是将回调函数传递给getEle():

getEle(id, callback){
  $.ajax({
    /* some options, */
    success: function(){
      var content = data;
      element[0] = id;
      element[1] = content;
      callback(element);
    }
  })
}

And then pass a function containing the code of what to do when you have the element content:

然后传递一个函数,其中包含元素内容时要执行的操作的代码:

getEle('myId', function(element){
  alert(element[1]);
});

#2


2  

Two things are failing here:

这里有两件事情失败了:

  • Variable scope - You define the variable content inside the AJAX callback. This makes it inaccessible from the surrounding code. You could omit the var and just write content = data which makes it accessible globally.
  • 变量作用域 - 您可以在AJAX回调中定义变量内容。这使得它无法从周围的代码中访问。您可以省略var,只需编写content = data,这样可以全局访问。

  • Asynchronicity - Becaus AJAX is asynchronous the script following the callback will be executed before the callback was executed. The only way to solve that problem is to use the callback as it's intended to.
  • Asynchronicity - Becaus AJAX是异步的,回调后的脚本将在执行回调之前执行。解决该问题的唯一方法是按照预期使用回调。

Take a look at this.

看看这个。

function getEle (id, callback) {
        var element = []; 

        $.ajax({
            url: 'slides.php',
            type: 'POST',
            data: {"id": id},
            success: function(data) {
                var content = data;
                element[0] = id;
                element[1] = content;

                callback(element);
            }
        });
    }
}

getEle ("someID", function(someElement) {
    alert(someElement);
});

#3


1  

Here's what's happening in your code:

这是您的代码中发生的事情:

  • the array "element" is initialized.
  • 数组“element”已初始化。

  • the AJAX call is made with a success callback function
  • AJAX调用是使用成功回调函数完成的

  • while it's waiting for that AJAX to run, it goes ahead with the rest of your code and alerts element[1], which doesn't exist yet
  • 当它正在等待AJAX​​运行时,它会继续执行其余的代码和警报元素[1],但它还不存在

  • the success callback runs and populates the array "element".
  • 成功回调运行并填充数组“元素”。

You might consider a global variable to solve this:

您可以考虑使用全局变量来解决此问题:

var element = []; 

function getEle (id) {
    $.ajax({
        url: 'slides.php',
        type: 'POST',
        data: {"id": id},
        success: function(data) {
            var content = data;
            element[0] = id;      // the global "element" is set
            element[1] = content;
        }
    });
}
// element[0] will exist now, but only after the AJAX call is complete

Alternatively, you could turn your AJAX into a synchronous call:

或者,您可以将AJAX转换为同步调用:

function getEle (id) {
    var element = []; 

    $.ajax({
        async: false,   // forces synchronous call
        url: 'slides.php',
        type: 'POST',
        data: {"id": id},
        success: function(data) {
            var content = data;
            element[0] = id;
            element[1] = content;
        }
    });
    alert(element[1]); // now it is set
    return element;
}

The only other option I can see is to keep everything tied up inside the "success" callback, which you already discovered works fine.

我能看到的唯一另一个选择是将所有内容都绑定在“成功”回调中,你已经发现它可以正常工作。

#4


0  

Your callback executes some time after the rest of your code finishes.

在其余代码完成后,您的回调会执行一段时间。

You need to pass the value back using a callback, the way $.ajax does.

你需要使用回调传递值,就像$ .ajax那样。

#5


-1  

Your alert ends up being undefined because the AJAX call is asynchronous. So while that AJAX call is waiting for the server's response, the script continues on to the alert, at which point element[1] is not yet defined.

您的警报最终未定义,因为AJAX调用是异步的。因此,当AJAX调用正在等待服务器的响应时,脚本继续执行警报,此时尚未定义元素[1]。

You should place your return element line inside of the success callback function.

您应该将返回元素行放在成功回调函数中。