对于$.ajax请求来说,如果层级比较多,程序看起来会比较乱,而为了解决这种问题,才有了$when...done...fail...then的封装,它将$.ajax这嵌套结构转成了顺序平行的结果,向下面的$.ajax写法,看起来很乱

$.ajax({
url: "/home/GetProduct",
dataType: "JSON",
type: "GET",
success: function (data) {
$.ajax({
url: "/home/GetProduct",
dataType: "JSON",
type: "GET",
success: function (data) {
$.ajax({
url: "/home/GetProduct",
dataType: "JSON",
type: "GET",
success: function (data) { }
}
}

而它实现的功能无非就是外层执行完成后,去执行内层的代码代码,看下面的$.when写法,就清晰多了

$.when($.ajax({
url: "/home/GetProduct",
dataType: "JSON",
type: "GET",
success: function (data) {
alert(JSON.stringify(data));
}
})).done(function (data) {
alert(data[0].Name);
}).done(function (data) {
alert(data[1].Name);
}).fail(function () {
alert("程序出现错误!");
}).then(function (data) {
alert("程序执行完成");
});

而对于这种ajax的封装,在比较流行的node.js里也需要被看到,这就类似于方法的回调技术!

在使用MVVM的KO上,更加得心应手,感觉$.when就是为了Knockoutjs而产生的!

//MVVM数据绑定
var MyModel = new model();
$.when($.ajax({
url: "/home/GetProduct",
dataType: "JSON",
type: "GET",
success: function (data) {
MyModel.PeopleList = ko.observableArray(data);//先为对象赋值
}
})).done(function (data) {
ko.applyBindings(MyModel);//再绑定对象
});

以后我们在进行前端开发时,应该多使用这种顺序的,平行的代码段,而少用嵌套的代码段,这只是大叔个人的见解。

原文:http://www.cnblogs.com/lori/p/5511846.html

最新文章

  1. chattr用法
  2. js库
  3. lenovo c340 centos 改键【尚无解】
  4. HashMap与TreeMap的区别
  5. Linux 下,mysql数据库报无法登陆错误:ERROR 1045 (28000): Access denied for use
  6. [ActionScript 3.0] AS3 绘制星形
  7. 华为OJ平台——计算字符串的相似度
  8. TI IPNC Web网页之流程分析
  9. C# 使用GDI+绘制漂亮的MenuStrip和ContextMenuStrip皮肤
  10. 20140527-ASP.NET中尖括号百分号用法
  11. MyBatis(3.2.3) - Paginated ResultSets using RowBounds
  12. ServiceStack.Redis常用操作 - 事务、并发锁
  13. Android string.xml error: Apostrophe not preceded by \
  14. QT实现不规则窗体
  15. xhost和XServer相关概念汇总
  16. hdu_5790_Prefix(trie+主席树)
  17. Cygwin在线安装指南
  18. centos 虚拟机桥接
  19. python gui 之 tkinter库
  20. Vue keep-alive的总结

热门文章

  1. MapReduce程序开发之流量求和(八)
  2. java单点登录系统CAS的简单使用
  3. iOS - 正则表达式判断邮箱、身份证..是否正确:
  4. 利用Xilinx中的ROM构造查找表来计算sin和cos的方法探讨
  5. 转:PHP之Traits
  6. A Statistical View of Deep Learning (V): Generalisation and Regularisation
  7. SharePoint 2010 产品六大功能模块
  8. python PIL except: IOError: decoder jpeg not available
  9. eclipse中tomcat内存溢出问题,报PermGen space
  10. 追踪CM_CONTROLCHANGE消息的产生和执行过程,可以较好的领会VCL的思想(就是到处通知,但耦合性很弱)