JavaScript : 함수간에 가변 값이 손실됩니다
-
11-09-2019 - |
문제
다음 코드가 있습니다
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
};
}
}
내 문제는 어쨌든 jQuery의 각 함수에서 JSON (ajax 호출의 객체)의 가치가 손실된다는 것입니다. 나는 왜 그런지, 어떻게 해결 해야하는지 알지 못했습니다. Google은 제가 찾고있는 답을주지 않습니다.
편집 1
실제 전화는 다음과 같습니다.
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);
};
해결책
JS Bin에서 문제를 재현하려고 시도하고 실패했습니다.
http://jsbin.com/ereha (편집 가능한 http://jsbin.com/ereha/edit)
지금까지 우리에게 보여준 코드는 완벽하게 괜찮아 보이므로 코드 나 시스템의 다른 부분으로 인해 문제가 발생해야합니다. 우리가 문제가 무엇인지 모른다면 우리는 모두 어둠 속에서 촬영합니다.
문제를 시도하고 재현하십시오 http://jsbin.com 그리고 우리는 거기에서 당신을 도울 수 있습니다.
완전한 소스 코드
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'
}
}
다른 팁
문제를 재현 할 수 없으므로 jQuery.each에는 아무 문제가없는 것 같습니다.
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);
alertName()
기능은 정확히 정확히 작동합니다. JSON 매개 변수는 내부에서 손실되지 않습니다 jQuery.each
기능
구현에 문제가있는 것 같습니다. 내가 한 것처럼 작업 샘플에 문제를 "압축"하고 우리가 스스로 시도 할 수 있도록 우리에게 보여주십시오 :)
확실합니까 json
대상입니다. 아마도 json-string? 당신보다 eval
사용하기 전에.
당신이 그것을 통해 그것을 얻는다면 $.ajax()
전화를 잊지 마십시오 dataType:'json'
옵션으로 ...
트레이 만약에() 사용할 조항 항목, JSON 데이터가 다양한 객체 인 경우 안건 각 객체를 포함하지만 이것은 내 가정 일뿐입니다.
나는 당신이 기능을 확인해야한다고 생각합니다 updateLiderContent 서버 측에서 JSON 응답 후에 호출됩니다.
아래 코드는 작동하지 않아야합니다.
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 );
따라서 때로는 의도없이 그런 일을했기 때문에 코드를 살펴보십시오.
아래 코드가 작동하고 서버가 실제로 올바른 JSON에 응답하는 경우 JSON 객체는 비워서는 안됩니다.
$.getJSON("/url/", {}, function(json){
//we call only after the response from server
updateSliderContent ( json );
});