Wrap the jquery function and return the value

Is it possible to wrap this code so that when called, the function returns a variable that binds the json object?

Example:

   function GetNewSomething() {
        var newtb = 0;
        $.get("/something/new",
                function (data) {
                    newtb = data;
                }
                );
        return newtb; // as of now this always returns undefined...
    }

Tried this way, but returned only undefined ..

Thanks in advance guys!

Yours faithfully,

+3
source share
4 answers

You can not. Ajax calls are asynchronous. You must pass a callback to your function:

function GetNewSomething(cb) {
    $.get("/something/new", cb);
}

and name it with:

GetNewSomething(function(data) {
    // do something with data
});

I wrote something about this .

Oh, and if the response is a JSON string, you can use .getJSONthat also decodes the response into a JavaScript object.

+6
source

.get() $.ajax(). AJAX , . , , , return newtb; $.get().

. :

function GetNewSomething(callback) {
    $.get("/something/new",
            function (data) {
                if( typeof callback === 'function' )
                    callback.apply(this, [data]);
            }
            );
}

GetNewSomething(function(data) {
     // do something with data
});
+3

$.get is asynchronous, so you pass it a function to call when the get request returns.

0
source

You can change to make $.geta $.ajaxand make it synchronous, as it $.getis just a wrapper for $.ajax:

function GetNewSomething() {
        var newtb = 0;
        $.ajax({url:"/something/new",
                type:"GET",
                async:false,
                success: function (data) {
                    newtb = data;
                }
          });
        return newtb; 
    }
0
source

Source: https://habr.com/ru/post/1786665/


All Articles