user705414
user705414

Reputation: 21200

Can we move the success function outside .ajax?

In the jquery example , I saw it is usually to define success function inside $.ajax() can we move it outside the body.

Upvotes: 1

Views: 784

Answers (3)

zclark
zclark

Reputation: 813

I use dojo more than I do jquery but the idea is the same. As long as the ajax call can reference to this outside function there is no reason why you cannot do that. You may run into the problem that when this ajax function is called it may no longer be able to get to the success function, depending on how you set things up. dojo.hitch(context, function) will fix this for you.

Upvotes: 0

Guffa
Guffa

Reputation: 700302

Yes, of course. You can assign an anonymous function to a variable:

var handleSuccess = function(data) {
  alert(data);
};

or you can make it a named function:

function handleSuccess(data) {
  alert(data);
}

For both alternatives you just use the name of the variable/function in the object:

$.ajax({
  success: handleSuccess
  ...
});

Upvotes: 2

c-smile
c-smile

Reputation: 27460

If you mean something like this:

function onSuccess()
{
    $(this).addClass("done");
}

$.ajax({
  url: "test.html",
  context: document.body,
  success: onSuccess 
});

then yes, you can do that.

Upvotes: 4

Related Questions