2009-08-29 8 views
1

Quel est le problème ici? (En plus d'avoir un code redondant). $.getJSON fonctionne comme prévu. Cependant $.postJSON ne fonctionne pas. Je peux inspecter $.fn via firebug et bien sûr, postJSON est listé. Cependant si j'essaye de l'appeler, j'obtiens une erreur définie sans fonction.jQuery.fn - Pourquoi ça ne marche pas?

jQuery.fn.getJSON = function(path, opts){ 
    this.extend(opts, { 
    url: path, 
    dataType: 'json', 
    type: 'GET' 
    }); 

    var invalid = opts.error; 
    opts.error = function(xhr, status){ 
    var data = $.httpData(xhr, 'json'); 
    if (invalid) 
     invalid(data); 
    } 

    this.ajax(opts); 
}; 

jQuery.fn.postJSON = function(path, data, opts) { 
    this.extend(opts, { 
    url: path, 
    data: data, 
    dataType: 'json', 
    type: 'POST' 
    }); 

    var invalid = opts.error; 
    opts.error = function(xhr, status){ 
    var data = $.httpData(xhr, 'json'); 
    if (invalid) 
     invalid(data); 
    } 

    this.ajax(opts); 
}; 

Répondre

5

jQuery.fn est une référence au prototype de l'objet jQuery, tous les objets jQuery construits ont accès à, de sorte que la fonction devient jQuery.prototype.postJSON. Si vous voulez déclarer comme une méthode statique, vous ne devriez pas spécifier le « .fn »

jQuery.fn.postJSON = function(){}; 

alert(typeof jQuery.prototype.postJSON); // function 
alert(typeof jQuery.postJSON); // undefined 

La raison jQuery.getJSON est une « fonction » est parce qu'il est une méthode native de l'objet jQuery (ce n'est pas la chose que vous déclarez, qui est jQuery.prototype.getJSON);

Questions connexes