有時候, 需要以不同的參數調用某個URL,並且在回調函數中仍然可以訪問正在使用的參數, 這時候, 需要使用閉包保存當前參數, 否則, 當回調函數執行時, 之前的參數很可能早已被修改爲最後一個參數了。 具體見代碼。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>關鍵詞搜索</title>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
var index;
var searchKeywords = ['一次', '一場', '舉行'];
var result = '第一種方式: <br/>';
for (index=0; index<3; index++) {
var keyword = searchKeywords[index];
$.ajax({
url: 'servlets/KeySearchServlet',
data: { 'keywords': keyword },
dataType: 'text',
timeout: 60000,
success: function(data) {
result += 'index: ' + index + ', keyword: ' + keyword + '<br/>';
$('#resultRegion').html(result);
// output unexpected:
// index: 3, keyword: 舉行
// index: 3, keyword: 舉行
// index: 3, keyword: 舉行
}
});
}
var result2 = '第二種方式: <br/>';
for (var index2=0; index2<3; index2++) {
(function(index2) {
var keyword = searchKeywords[index2];
$.ajax({
url: 'servlets/KeySearchServlet',
data: { 'keywords': keyword },
dataType: 'text',
timeout: 60000,
success: function(data) {
result2 += 'index: ' + index2 + ', keyword: ' + keyword + '<br/>';
$('#resultRegion2').html(result2);
// output the expectation result
// index: 0, keyword: 一次
// index: 1, keyword: 一場
// index: 2, keyword: 舉行
}
});
})(index2);
}
});
</script>
<style type="text/css">
#result {
float: left;
margin: 20px 50px;
}
#resultRegion, #resultRegion2 {
overflow-y: auto;
border: 3px outset #f58220;
width: 500px;
height: 100px;
padding: 10px 10px 10px 30px;
font-size: 11pt;
/* Gecko browsers */
-moz-border-radius: 5px;
/* Webkit browsers */
-webkit-border-radius: 5px;
/* W3C syntax - likely to be standard so use for future proofing */
border-radius:10px;
}
</style>
</head>
<body>
<div id="result">
<p id="searchTip"> 結果對比: </p>
<div id="resultRegion">
</div>
<div id="resultRegion2">
</div>
</div>
</body>
</html>
結果: