在ajax调用中的这个概念

时间:2016-03-04 06:23:31

标签: jquery ajax

 function Tour(el) {
    var tour = this;
    this.el = el;
    this.fetchPhotos = function() { 
    $.ajax('/photos.html', {
       data: {location: tour.el.data('location')},
       context: tour,
       success: function(response) {
          console.log(this===tour);
          this.el.find('.photos').html(response).fadeIn();
       },
       error: function() {
         this.el.find('.photos').html('<li>There was a problem fetching  the latest photos. Please try again.</li>');
       },
       timeout: 3000,
       beforeSend: function() {
          this.el.addClass('is-fetching');
       },
       complete: function() {
          this.el.removeClass('is-fetching');
       }
    });
  }
  this.el.on('click', 'button', this.fetchPhotos);
}
$(document).ready(function() { 
  var paris = new Tour($('#paris'));
  var london = new Tour($('#london '));
});

控制台日志输出成功功能= true

上面的代码片段来自教程。我有2个与此相关的查询&#39;对象

  1. &#39;游&#39; &安培; &#39;这&#39;是相同的(如输出所示),但当我更换&#39; tour&#39;用这个&#39;在ajax调用的数据选项中,它停止工作。为什么会这样?

  2. 为什么我们不使用&#39; tour&#39;在其他函数内部 - error,beforeSend.etc。

  3. 请有人帮忙。

1 个答案:

答案 0 :(得分:1)

这一切都与Ajax调用中的“context”关键字有关。 Context告诉它在调用其中一个Ajax回调(例如成功)时会出现什么“this”。在你的情况下,你将'tour'作为上下文传递,这意味着在你的成功函数中,'this'等于'tour'。