There is a function that represents the framework of ajax requests:

/*Структура для ajax-запросов: method - тип запроса (get,post,update,delete), убрано в связи с jsonp async - boolean, вкл/откл асинхронность, address - url запроса, transport_data - данные на отправку, function_on_success - функция, которая выполнится при удачном запросе, parameters_for_fun_as_obj - объект с набором параметров для удачной функции*/ function create_ajax(async,jsonp_callback,address,transport_data,function_on_success,parameters_for_fun_as_obj){ $.ajax({ method: 'get', dataType: 'jsonp', //jsonp: false, jsonpCallback: jsonp_callback, contentType: "text/json; charset=utf-8", async: async, url: address, global: true, crossDomain: true, data: transport_data, success: function (data) { function_on_success(data, parameters_for_fun_as_obj); } }); 

How to assign the value of a local variable in the query results function using this framework? Thus it is impossible to make - the request is executed, the function is also, the data is not empty, but is not assigned.

 function my_function(){ var temp; temp = create_ajax(true,'result',address,'',return_data); } var return_data = function(data){ return data; } 

Reported as a duplicate by members aleksandr barakin , Grundy , Denis , cheops , Bald Jul 18 '16 at 5:08 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • No Impossible. - Alexey Ten
  • @Alexey Ten - I would not say that it is impossible. At a minimum, insert text with data into an element on the page, then parse it into an object. But this is too crutch - Ajmda
  • It won't "assign a local variable" - Alexey Ten

2 answers 2

Asynchronous code, promises will help. Here is an example implementation on jQuery:

 function ajaxRequest(async,jsonp_callback,address,transport_data,function_on_success,parameters_for_fun_as_obj){ return $.ajax({ method: 'get', dataType: 'jsonp', //jsonp: false, jsonpCallback: jsonp_callback, contentType: "text/json; charset=utf-8", async: async, url: address, global: true, crossDomain: true, data: transport_data }); } //Этот код выполнится только после успешного выполнения ajax запроса ajaxRequest(async,jsonp_callback,address,transport_data,function_on_success,parameters_for_fun_as_obj).then(function(data){ my_function(data); }); 
  • $.ajax already returning a promise, there is no need to do $.Deferred() manually, well, the answer from the server is lost now, because there is no access to it inside my_function - Grundy
  • Oh, thanks, I refactored the code a bit. - d4rkm3z

If I understand your idea correctly:

 function what_doing(data){ return data * 1.5; } function sum(a,b,f_name){ var result = a+b; if(result > 0){ return f_name(result); }else{ return false; } } function go(){ var temp; temp = sum(5,3,what_doing); console.log(temp); // ->12 } go();