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.

    评论

报告相同问题?