Brad
Brad

Reputation: 2237

How does jquery return functions like success and error

I've looked though the jquery code, and it's not clear to me. How do I make my own function return success or error like in the following code:

   $.ajax({
      type: "GET",
      url: "/some.xml",
      success: function()
      { /** found! **/},
      error: function(xhr, status, error) {
        if(xhr.status==404)
          { /** not found! **/}
      }
    });

Upvotes: 0

Views: 464

Answers (2)

thangcao
thangcao

Reputation: 1899

For more options (success, error, state, ...), I recommend to use Deffered object. http://api.jquery.com/category/deferred-object/

Example:

    function MyFunction(parameter){
        var def = $.Deferred();
        if(DoSomeThing()){
           def.resolve();
        }
        else{
           def.reject()
        }
        return def;
    }

Usage: ...

MyFunction(xxx).then(function(){
// Success case
})
.fail(function(){
//Fail case
});

Upvotes: 0

Daniel Imms
Daniel Imms

Reputation: 50229

$.ajax passes in an object which has success and error properties on it that are functions. In the function it will then call either success or error depending on the result. This example might help you understand better.

jsFiddle

function ifTrue(bool, params) {
    if (bool)
        params.success();
    else
        params.error();
}

ifTrue(true, {
    success: function () {
        alert('success');
    },
    error: function () {
        alert('error');
    }
});

ifTrue(false, {
    success: function () {
        alert('success');
    },
    error: function () {
        alert('error');
    }
});

Upvotes: 1

Related Questions