How to pass Object context to jQuery.ajax JSONP ca

2020-03-03 06:35发布

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 service provider).

I'll give a simplified example:

function Person(anId) {
 this.name;
 this.id = anId;
 var self = this;
 this.loadName = function() {
  $.ajax({
   url: "jsonp.json",
   dataType: "jsonp",
   jsonpCallback : "handleJSON",
   data : {id: this.id},
   context: self,
   success: function (data) {
    self.name = data.name;
   }
  });
 }
}

var handleJSON = function(data) {
 console.log("received " + data.name );
}

var a = new Person(234);
a.loadName();
var b = new Person(345);
b.loadName();



The example above works perfectly, the console outputs the line of the handleJSON function. But in this function I don't have a reference to the original object that's calling it. I want that the success function is called instead: here I can refer to the self variable.

There are several possible solutions, but I don't get any running.

  1. I'll intercept the callback name that jQuery generates for me and put it as a value in the jsonpCallback parameter. I presume that this function delegates to the specified success function, from which I can access this. But I see no way how to obtain that generated name.
  2. I'll specify the context object like I did in the example. The jQuery docs states that this object would be available to the callback handler. However I cannot find how this context is exposed to e.g. the handleJSON function from my example.

Currently I found a solution with the jquery-jsonp from google code. But still I'm very curious how to solve the problem as described at 2. Because I think the jQuery reference states that it could be handled like that. What makes me dependable on less third party libraries.

Can someone show me how to access the context in a JSONP callback handler using jQuery?

1条回答
兄弟一词,经得起流年.
2楼-- · 2020-03-03 06:54

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();
查看更多
登录 后发表回答