How to pass Object context to jQuery.ajax JSONP callback?

前端 未结 1 1451
轮回少年
轮回少年 2021-01-02 21:58

I run into problems to pass a javascript object context into the callback handler of a JSONP ajax request, when the ajax provider predefines its callback. (Flickr is the ser

相关标签:
1条回答
  • 2021-01-02 22:21

    Just leave the jsonpCallback property alone, and let jQuery create the function that gets called and it's function name. That function will call the success callback that you specify, with the context you specify.

    function Person(anId) {
     this.name;
     this.id = anId;
     this.loadName = function() {
      $.ajax({
       url: "jsonp.json",
       dataType: "jsonp",
       data : {id: this.id},
       context: this,
       success: function (data) {
        this.name = data.name;
       }
      });
     }
    }
    
    var a = new Person(234);
    a.loadName();
    var b = new Person(345);
    b.loadName();
    
    0 讨论(0)
提交回复
热议问题