JavaScript: Variabile Valore si perde tra le funzioni
-
11-09-2019 - |
Domanda
Ho il seguente codice
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
};
}
}
Il mio problema è che in qualche modo, il valore di JSON (che è un oggetto da un AJAX chiamata) si perde nella ogni funzione di jQuery. Non ho ancora scoperto il perché, né come risolverlo. Google non mi dà la risposta che sto cercando.
Modifica 1
Ecco la chiamata effettiva.
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);
};
Soluzione
Ho tentato, e fallito, di riprodurre il problema su JS Bin:
http://jsbin.com/ereha (modificabile tramite http://jsbin.com/ereha/edit )
Il codice che ci hai mostrato finora sembra perfettamente bene, in modo che il problema deve essere causato da qualche altra parte del codice o del sistema. Siamo tutti appena riprese al buio, se non sappiamo qual è il problema.
Si prega di cercare di riprodurre il problema su http://jsbin.com e vi possiamo aiutare da lì.
Completa Codice Sorgente
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'
}
}
Altri suggerimenti
Sembra che ci sia niente di sbagliato con la jQuery.each come io non riesco a riprodurre il 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);
funzione alertName()
funziona esattamente come dovrebbe. Il parametro json non si perde all'interno della funzione jQuery.each
Sembra essere un problema sulla vostra implementazione, qualcosa che non ci stai raccontando. Si prega di cercare di "comprimere" il problema ad un campione a lavorare come ho fatto io e mostrare noi in modo che possiamo provare a da soli:)
Sei sicuro json
è un oggetto. Forse è un JSON-stringa? Quanto deve eval
prima dell'uso.
Se lo si ottiene tramite chiamata $.ajax()
non dimenticare di aggiungere dataType:'json'
come opzione ...
vassoio nel se () clausola utilizzare item.action , perché se i dati JSON è un array di oggetti, articolo sarà contenere ogni oggetto, ma questa è solo la mia ipotesi
Credo che si dovrebbe assicurarsi che la funzione di updateSliderContent è chiamato dopo la risposta JSON dal lato server.
Il codice qui sotto non dovrebbe funzionare:
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 );
Quindi, per favore dare un'occhiata al codice perché a volte abbiamo fatto una cosa del genere senza intenzione.
Il codice qui sotto dovrebbe funzionare e l'oggetto JSON non deve essere vuoto se il server realmente la risposta JSON corretta.
$.getJSON("/url/", {}, function(json){
//we call only after the response from server
updateSliderContent ( json );
});