在開發專案時,前端偶爾會遇到兩個比較隱蔽的問題。本文記錄筆者實際碰到的案例:IE7 的 URL 參數過長報錯,以及 this 作用域的陷阱,並附上 respective 解法。
現象:專案在 IE6、IE8 下都沒問題,但在 IE7 卻因 GET 參數過長而引發 HTTP Status 122 報錯。
原因:IE7 對 GET 的字串長度有限制,網路上普遍建議「在 Ajax 應用中盡量別用 GET,因為 IE7 在超過 2032 個字元的查詢字串時會出問題」。
解法:把原本採用 jsonp get 的資料方法,改為一般的 POST 資料方法,即可避開 URL 長度限制。
原因:this 若不是在物件內部,預設會指向 window 這個大物件。而下圖中若把 this 放在一個 ajax 的 success 回呼裡,它指的就是該 ajax 設定物件,而非我們期望的外層物件:
var test = {};
test.getflash = 2;
test.test = function(){
alert(this.getflash); // 2
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert(this.getflash); // undefined!
}
});
};
解法是在進入回呼前,先把 this 存到一個區域變數,回呼中改用這個變數:
test.test = function(){
var thisValue = this; // 先保留外層的 this
alert(thisValue.getflash); // 2
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert(thisValue.getflash); // 2
}
});
};
這兩個問題都很典型。第一個提醒我們:GET 的查詢字串有長度上限(各瀏覽器不同),資料量大時應改用 POST。第二個則是 JavaScript 每個新手都會踩的 this 作用域陷阱——回呼函式會有自己的 this,若要在其中存取外層物件的 this,就得先用 that = this 或 self = this 把它存起來(這是社群約定俗成的寫法)。當然,若能用箭頭函式,由於它不綁定自己的 this、會沿用外層的 this,這個問題就能自然化解。