有时候, 需要以不同的参数调用某个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>

结果:

最新文章

  1. C#/VB.NET 向PowerPoint文档插入视频
  2. ZOJ 3911 线段树
  3. Product of Array Except Self
  4. 161209、简要分析ZooKeeper基本原理及安装部署
  5. PHP受保护的类和私有类什么区别
  6. FileStream操作文件读写
  7. hbase 单机模式安装
  8. ubuntu, Debian, CentOS
  9. Python 生成的页面中文乱码问题
  10. Android sdk配置 常见问题及处理方法
  11. [bzoj]2962序列操作
  12. 页面jquery调试的一个宝贵经验(类似于Eclipse中的写出一个对象点它的方法时候用alt加/可以跳出来它所有的方法)
  13. ubuntu下截图工具推荐 -- [deepin-scrot]
  14. mysql插入一条记录时有自增id怎么办
  15. 题解——洛谷P3275 [SCOI2011]糖果
  16. Java语法基础DayFive
  17. [uart]1.Linux中tty框架与uart框架之间的调用关系剖析
  18. Linux 期中架构 PHP
  19. CSS属性之attr()
  20. vue2 使用 element-ui

热门文章

  1. mysql相似于oracle的to_char() to_date()方法
  2. [LintCode] Wiggle Sort 扭动排序
  3. 细说jQuery原型的创建和实现原理,并用实例简单模仿
  4. c++用双向链表实现模板栈
  5. CSS Bugs 解决方案
  6. vue 一些开发姿势
  7. 学Python后到底能干什么?
  8. modifiedvalues 主程序测试
  9. BizTalk2010动手实验(二)第一个BizTalk应用
  10. centos安装vsftp