开发者

Calling an object after an ajax call returns

I built the following object:

 var cls = {
    offset : 0,
    onSuccess : function(data) {
        alert(this.offset);
    }
};

$(document).ready(function(){
    $("form").submit(function() {
              $.post(
                  "/ajax",
                  {},
                   c开发者_开发百科ls.onSuccess
               );
     });
});

When the ajax returns and onSuccess of cls is called then I get an alert of undefined.

If I just call cls.onSuccess() then the alert returns 0 ex expected. Any reason for this behavior?


don't use "this". it will not refer to what you expect to refer.

use window.alert(cls.offset);

it's quite long to explain, but this should help you.


You need to give the AJAX function a context for the callback. I would use .ajax() instead of .post() and pass cls as the context:

$.ajax({
  url: "/ajax",
  context: cls,
  type: "POST",
  success: cls.onSuccess
});


this is not your object, cls, anymore. You are passing a function reference, onSuccess to the post call.


You are passing just the function, independent of the object. If you wrap it in a function it should work:

$(document).ready(function(){
    $("form").submit(function() {
              $.post(
                  "/ajax",
                  {},
                   function(data){
                      cls.onSuccess(data);
                   }
               );
     });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜