jQuery 1.4がリリースされましたが、jQuery.param()の変更点が割とドラスティックで、少しハマってしまったのでメモしておきます。
オブジェクトからクエリストリングを作る場面の動作が、デフォルトでRailsライクなシリアライズ(Redmineのチケット一覧を絞り込む時のパラメータの様に、ネストしたオブジェクトや配列を展開)をするようになりました。
どうもオブジェクトのプロパティを列挙してFunction型だった時に、windowスコープで実行結果を取りに行くっぽいです。
jQuery.param()の第2引数traditionalにtrueを指定すると、これまで通りの動作をします。
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.js"></script>
<script type="text/javascript">
var MySize = function(x, y) {
this.x = x;
this.y = y;
}
MySize.prototype.toString = function() {
return String(this.x) + "," + String(this.y);
};
var s = new MySize(50, 50);
var params = {
"size": s
};
// size[x]=50&size[y]=50&size[toString]=undefined,undefined
console.log(decodeURIComponent($.param(params)));
// size=50,50
console.log(decodeURIComponent($.param(params, true)));
</script>
undefinedになる程度ならまだ良いのですが(良くないけど)、以下のような関数を定義していると、実行時エラーになってしまいます。
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.js"></script>
<script type="text/javascript">
var MySize = function(x, y) {
this.x = x;
this.y = y;
}
MySize.prototype.toString = function() {
return String(this.x) + "," + String(this.y);
};
MySize.prototype.isWide = function() {
return this.x > this.y;
};
MySize.prototype.isNarrow = function() {
return this.x < this.y;
};
MySize.prototype.isSquare = function() {
return !this.isWide() && !this.isNarrow();
};
var s = new MySize(50, 50);
// false
console.log(s.isWide());
// false
console.log(s.isNarrow());
// true
console.log(s.isSquare());
var params = {
"size": s
};
// s.isSquare.call(window); => this.isWide is not a function
console.log(decodeURIComponent($.param(params)));
// size=50,50
console.log(decodeURIComponent($.param(params, true)));
</script>
jQuery 1.4にアップデートした時に、今まで動いていたjQuery.ajax()を利用している箇所が突然動かなくなった場合は、オプション引数のtraditionalにtrueを渡したり、またはjQuery全体のajaxSettingsを変更してしまうのが良いようです。
// ajax()のtraditionalにtrueを指定
$.ajax({
"url": "http://www.example.com/",
"data": params,
"success": onSuccess,
"traditional": true
});
// jQuery全体の動作設定を変更
$.ajaxSettings.traditional = true;
最近のツッコミ
参号館
日記(ariyasacca)