A
A
akula222019-10-15 14:39:04
JavaScript
akula22, 2019-10-15 14:39:04

How to access a variable inside a function in jquery?

I do calculations and in one condition I need to make a request to the database

$.post(
                    "/calc/sticker/get-options", {},
                    function (options) {
                         $options = JSON.parse(options);
                    });
            }

the $options variable is only visible inside the function,
how do I access it further in the calculations?
I read about the visibility of variables, tried var does not help, tell me how to get access, or how to organize a function with a result return

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey Sokolov, 2018-07-24
@Chefranov

It is better to do the replacement with regular expressions so that all occurrences are replaced at once, and not one at a time.
Which bb-code to which class to change is easier to set with a dictionary object.
Something like this:

// словарь   bbcode: className
const dict = {
  'info': 'info-text',
  'admin': 'admin-text',
};

var tds = document.getElementsByTagName("td");
for (let k = 0; k < tds.length; k++) {
  let td = tds[k];
  if (td.className !== 'posttdMessage') continue;

  let s = td.innerHTML;
  for(let bb in dict) {
    let re_open = new RegExp('\\[' + bb + '\\]', 'ig');
    let re_close = new RegExp('\\[/' + bb + '\\]', 'ig');
    s = s.replace(re_open, '<div class="' + dict[bb] + '">').replace(re_close, '</div>');
  }
  td.innerHTML = s;
}

R
Ruslan Ruslanov, 2019-10-15
@dasauser

one option is to make this variable global.
well, the closure, in fact, is the closure for that, in order to work out and forget.
although I could be wrong.

G
Gennady, 2019-10-15
@GssGenic

options = $.post( "/calc/sticker/get-options", {});
$options = JSON.parse(options);
Maybe so?

E
EN, 2019-10-16
@rudev

var $options; // глобальная переменная

$.post( "/calc/sticker/get-options", {},  function (options) {
    $options = JSON.parse(options);
});

console.log($options); // вывод в консоль результатов

ps If you need to use these results everywhere, then you need to declare at the highest level
var $options;. But you should always remember that you can overwrite data by accident.
You can declare a global container where all data will be stored. For example:
var container = {
    options:{},
    pictures:[],
    selected:"element_name",
    // другие данные
};

Anywhere in the JS code, you make an assignment like this:
container.options = JSON.parse(options); // присвоение

//получение данных 
var $options = container.options;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question