jquery ajax context

 1 function yflib_roomList(tpl) {
 2     var target = $(".roomList > li");
 3     var _this = null;
 4     $(".roomList > li").each(function(i, item) {
 5         _this = $(this);
 6         var _CloudID = _this.attr("CloudID");
 7         getRoomDetailByID(_this, _CloudID, onDataRecieved);
 8     });
 9     function onDataRecieved(ret) {
10         var data = ret.data;
11         var html = tpl;
12         //遍历数据集,替换模板中相应的数据项
13         $.each(data, function(key, value) {
14             var re = new RegExp("{{\s*data\." + key + "\s*}}", "g"); //  在双引号里面需要转义
15             //var re = new RegExp("{{data\.CloudID}}","g"); //  在双引号里面需要转义
16             html = html.replace(re, value);
17         });
18         $(this).append(html);
19     }
20 }
 1 function getRoomDetailByID(context, CloudID, callback) {
 2     var url = "?s=Api/getRoomDetailByID";
 3     $.ajax({
 4         context: context, //传入上下文变量
 5         url: url,
 6         data: {"CloudID": CloudID},
 7         dataType: "json",
 8         success: callback,
 9         error: function(xhr, status) {
10             $("#rs").html("return:<br />" + xhr.responseText);
11         }
12     });
13 }

在ajax传入了context后,在回调函数里面使用$(this)即可以获得上下文对象,例如object

原文地址:https://www.cnblogs.com/trying/p/3396831.html