2013-03-25 123 views
-2

我正在一個項目中,我有一個對象有兩個主要方法,「保存」和「關聯」,都使用jQuery ajax調用服務器。

這兩種方法都以回調函數作爲參數,但只有其中一種回調方法正在啓動,即使在Chrome開發工具中查看所有保存/關聯帖子,並從服務器返回有效數據。

這裏有三件我的工作:

Entity.prototype.save = function(callback) 
{ 
    var self = this; 
    $.ajax({ 
     url: '/Entity/Create', 
     type: 'POST', 
     dataType: 'json', 
     contentType: 'application/json; charset=utf-8', 
     data: JSON.stringify(model), 
     success: function (data){}, 
     error: function (xhr, status, err) { }, 
     complete: function (data) 
     { 
      console.log(self.get('_id') + ' saved.') 
      if(callback) 
        callback(data.responseText); 
     } 
    }); 
} 

Entity.prototype.relate = function(relatedEntityId, isRelate, callback) 
{ 
    var self = this; 
    var action = isRelate ? 'Relate' : 'Unrelate'; 

    $.ajax({ 
     url: '/Entity/' + action, 
     type: 'POST', 
     dataType: 'json', 
     contentType: 'application/json; charset=utf-8', 
     data: JSON.stringify({ primaryEntityId: self._id.value, relatedEntityId: relatedEntityId }), 
     done: function (data) { }, 
     fail: function (xhr, status, err) { }, 
     always: function (data) 
     { 
      console.log(self.get('_id') + 'related to ' + relatedEntityId); 
      if(callback) 
       callback(data.responseText); 
     } 
    }); 
} 


// from main code: 

entity.save(function (id) // this callback fires 
{ 
    // request is a previously saved 'entity' 
    request.relate(id, true, function (id) // this callback does not 
    { 
     console.log('related callback completed.'); 
    }); 
}); 

我不知道爲什麼第二次回調(從request.relate)不火,當$就調用設置(在「完成」處理程序中觸發回調)

我正在測試最新版本的Chrome(25.0.1364.172米)。也在Firefox 19中測試過,結果相同。

回答

5

donefail and always不是有效的ajax屬性,它們用於延遲對象。

您需要使用錯誤/成功/完成。

+0

我覺得啞巴。謝謝你指出我的錯誤。如果我能投票自己,我會的。 – keithhamilton 2013-03-25 21:44:21

+1

標記他的回答正確:) – iAmClownShoe 2013-03-25 21:47:55

+0

我不得不等待5分鐘來做到這一點。這當然是正確的。 – keithhamilton 2013-03-25 22:02:48