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
};
}
}
私の問題は、どういうわけか、json (AJAX 呼び出しからのオブジェクト) の値が jquery の各関数で失われることです。その理由も解決方法もまだわかりません。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 そこからお手伝いさせていただきます。
完全なソースコード
インデックス.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>
テスト.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文字列?あなたが使用する前にそれをeval
なければならないより。
あなたは$.ajax()
の呼び出しを介して、それを取得する場合のオプションとしてdataType:'json'
を追加することを忘れないでください...
トレイ、JSONデータは、オブジェクトの配列である場合ので、の項目のであろう各オブジェクトが含まれているが、これは私の仮定である。
機能を確認したほうがいいと思います スライダーコンテンツの更新 サーバー側からの 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 );
});