JavaScript: Valor variável se perde entre as funções
-
11-09-2019 - |
Pergunta
Eu tenho o seguinte código
function updateSliderContent(json) { //<- json defined here is correct
var screen_order = json.screen_order.split('_');
jQuery.each(screen_order, function(i, item) {
var screen_id = item;
//at this point it is not, thus the function does not execute whatever is in the if blocks
if (json[screen_id].action == 'add') {
//doSomething
} else if (json[screen_id].action == 'remove') {
//doSomthingElse
};
}
}
O meu problema é que de alguma forma, o valor de JSON (que é um objeto de uma chamada de AJAX) se perde na cada função do jQuery. Eu ainda não descobri por que, nem como resolvê-lo. Google não me dá a resposta que eu estou procurando.
Editar 1
Aqui está a chamada real.
function updateSlider() {
var screenOrder = '';
jQuery('div#slider td').each(function(i, item) {
screenOrder += this.abbr + '_';
})
var ajaxData = {
sid: sid,
story: story,
date: theDate,
screenOrder: screenOrder,
mode: 'ajax_update_slider'
};
jQuery.ajax({
data: ajaxData,
dataType: 'json',
success: function (json) {
updateSliderContent(json);
}
});
theDate = Math.round(new Date().getTime()/1000.0); //UNIX Timestamp
sliderTimer = setTimeout('updateSlider();',15000);
};
Solução
Eu tenho tentado, sem sucesso, reproduzir o seu problema em JS Bin:
http://jsbin.com/ereha (editável via http://jsbin.com/ereha/edit )
O código que você mostrou-nos até agora parece perfeitamente bem, então o problema deve ser causada por alguma outra parte do seu código ou sistema. Estamos todos apenas atirando no escuro, se não sabemos qual é o problema.
Por favor, tente reproduzir o problema em http://jsbin.com e podemos ajudá-lo a partir daí.
completa Source Code
index.html
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>http://stackoverflow.com/questions/1831384/javascript-variable-value-gets-lost-between-functions</title>
<script type="text/javascript" src="http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajaxSetup({url: 'test.json'});
function updateSliderContent(json) { //<- json defined here is correct
var screen_order = json.screen_order.split('_');
jQuery.each(screen_order, function(i, item) {
var screen_id = item;
//at this point it is not, thus the function does not execute whatever is in the if blocks
if (json[screen_id].action == 'add') {
console.log(screen_id, 'action add');
} else if (json[screen_id].action == 'remove') {
console.log(screen_id, 'action remove');
};
});
}
function updateSlider() {
var ajaxData = {};
jQuery.ajax({
data: ajaxData,
dataType: 'json',
success: function (json) {
updateSliderContent(json);
}
});
// theDate = Math.round(new Date().getTime()/1000.0); //UNIX Timestamp
sliderTimer = setTimeout('updateSlider();',15000);
};
$(updateSlider);
</script>
</head>
<body>
</body>
</html>
test.json
{
'screen_order': 'foo_bar_baz',
'foo': {
'action': 'add'
},
'bar': {
'action': 'add'
},
'baz': {
'action': 'remove'
}
}
Outras dicas
Parece haver errado nada com o jQuery.each como eu não posso reproduzir o seu problema.
function alertName (json) {
var a = new Array();
a.push(1);
a.push(2);
jQuery.each(a, function(i, item) {
alert(json[0].name);
alert(json[1].name);
});
}
var andre = { name: "André" }
var joana = { name: "Joana" }
var arrayOfJson = new Array();
arrayOfJson.push(andre);
arrayOfJson.push(joana);
alertName(arrayOfJson);
função alertName()
funciona exatamente como deveria. O parâmetro JSON não está perdido na função jQuery.each
Parece ser um problema em sua implementação, algo que você não está nos contando sobre. Por favor, tente "compressa" o problema a uma amostra de trabalho como eu fiz e mostrar-nos para que possamos tentar em em nosso próprio:)
Você tem certeza json
é um objeto. Talvez seja um json-corda? Do que deveria eval
-lo antes de usar.
Se você obtê-lo através de chamada $.ajax()
não se esqueça de fazer dataType:'json'
como uma opção ...
bandeja na
Eu acho que você deve certificar-se a função updateSliderContent é chamado após a resposta json do lado do servidor.
O código abaixo não deve trabalho:
var json = {};
$.getJSON("/url/", {}, function(data){
json = data;
});
//we call our function before the server response
//and the json will be just blank object
updateSliderContent ( json );
Então, por favor, dê uma olhada no seu código, porque às vezes nós fizemos algo como que sem intenção.
O código abaixo deve funcionar eo objeto JSON não deve estar em branco se o servidor realmente a resposta JSON correto.
$.getJSON("/url/", {}, function(json){
//we call only after the response from server
updateSliderContent ( json );
});