jQuery.ajax()成功回调存储数据恢复 [英] jQuery.ajax() success callback store data to return

查看:267
本文介绍了jQuery.ajax()成功回调存储数据恢复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个PHP脚本中的一些数据的一个项目现在。所有的例子,我发现搜索AJAX回调函数回调本身使用的数据了,但我希望获取数据,并将其存储在一个方式准备返回。

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.

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;
}

某处在我的剧本的一些功能需要 getEle(一节),但我得到的是未定义。 有没有办法做我想要什么?还是有可能是更好的方式来做到这一点?

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()

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

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

再经过含有当你有该元素的含量做什么的code函数:

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]);
});

这篇关于jQuery.ajax()成功回调存储数据恢复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆