jQuery: making AJAX data accessible outside AJAX methods

jQuery: making AJAX data accessible outside AJAX methods

A simple test on how to make AJAX data returned by jQuery methods accessible outside such methods.

As you know, all jQuery AJAX methods work just like sandboxes, in the sense that the data returned from the server come encapsulated within the method used to retrieve them. In the following test, I've tried to make this data accessible outside AJAX methods.

We're going to test a simple JSONP request. We define a global empty object and then we copy each property and value of the returned JSON object into the global one:

var $data = {};

$.ajax({
    type: 'GET',
    url: 'http://jsfiddle.net/echo/jsonp/', 
    dataType: 'jsonp',
    data: {
        text: 'some text',
        par1: 'another text'
    },
    success: function(data) {
        var _data = data;
        $.each(_data, function(p, v) {
            $data[p] = v;
        });
    }
});

console.log($data); 

/*
    Object
    _: "1341688097030"
    par1: "another text"
    text: "some text"
    __proto__: Object

*/

A more efficient solution is to use $.extend() to clone the returned object. Anyway, there are still many aspects to make clear.

Test

Live test