weixin_33725239 2015-12-17 22:07 采纳率: 0%
浏览 15

从AJAX存储变量

How do I gain access to variables that come from a ajax request that is returned from a function? I can console.out the variable, but I can't seem to store it outside the scope.

How it looks like:

  1. In the html:

    function my_ajax() {

    var stuff = 'stuff';
    return $.ajax({
        type: "POST",
        url: "file.php",
        data: {"something": "wrong"}
    }); /* end ajax */  
    

    } /* end my_ajax() */

...then in the js-file:

my_ajax().then(function(response){
        var elements = jQuery.parseJSON(response);              
        var one = elements.one;
        var two = elements.two;

//now say that I need to use 'one' outside this function. I try this:

    stuff(elements);

    });

//this works

function stuff(el) {
var something = el.one;
console.log(something);
}

//this doesn't work

function stuff(el) {
var something = el.one;
return something;
}

//this works

var try_obj = {
    please_work: function(el) {
        var something = el.one;
        console.log(something);
    }
};

So how do I store variables from ajax of this nature so that I can reuse them on the html-page or in the js-file? I need to send them back with another ajax request.

  • 写回答

5条回答 默认 最新

  • weixin_33674437 2015-12-17 22:12
    关注

    If you already have an object like try_obj accessible globally then it's as simple as:

    my_ajax().then(function(response){
        var elements = jQuery.parseJSON(response);              
        var one = elements.one;
        var two = elements.two;
    
    //now say that I need to use 'one' outside this function. I try this:
    
    try_obj.ajaxStore = elements;
    
    });
    

    Then just call try_obj.ajaxStore from wherever you need to.

    Here is a alternative. You could set a global variable:

    my_ajax().then(function(response){
        var elements = jQuery.parseJSON(response);              
        var one = elements.one;
        var two = elements.two;
    
    //now say that I need to use 'one' outside this function. I try this:
    
    window.ajaxStore = elements;
    
    });
    

    Then ajaxStore can be used anywhere. Usually you want to avoid using global variables, however.

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器