2014-03-01 49 views
0

我正在開始我的sailsJS使用過程。使用SailsJS和MongoDB進行Ajax更新

我有一個關於如何通過jquery ajax請求更新我的模型與MongoDB的問題。 這裏是我的代碼:

jQuery("a#identity-edit").on("click", function() { 

    $.ajax({ 
     url: '/character/update', 
     method: 'POST', 
     data: { 
      id: $("a#identity-edit").attr("data-id"), 
      name: 'myNewName' 
     }, 
     success: function() { 
      window.location('/character/show/'+$("a#identity-edit").attr("data-id")); 
     }, 
     failure: function(msg) { 
      alert("Fail : " + msg); 
     }, 
     error: function(xhr, status, text) { 
      alert(text); 
      var response = jQuery.parseJSON(xhr, responseText); 
      alert(response.error); 
     } 
    }); 

不幸的是,這個碼是「錯誤」的處理程序有一個空的文本擦肩而過......

你能不能給我解釋一下什麼是錯的嗎?

由於通過提前

西里爾

+0

什麼是錯誤的是,你可能有一個服務器端錯誤,這不是服務器代碼。你需要在你的問題中顯示那部分。 –

+0

對不起,但我不明白你的答案 –

+1

這不是一個答案,它是一個評論。您的問題**僅**顯示您的客戶端代碼,您POST到服務器上的端點。我們需要看看那裏發生了什麼。 –

回答

0

投遞通過jQuery的API,你需要做一些更多的工作,讓您的數據準備:

$.ajax({ 
    url: '/character/update', 
    method: 'POST', 

    // Tell the server we're sending JSON--not strictly necessary with Sails, 
    // but recommended. 
    contentType: 'application/json', 

    // Don't URLencode data 
    processData: false, 

    // Stringify the data--otherwise it will send "[object object]" 
    data: JSON.stringify({ 
     id: $("a#identity-edit").attr("data-id"), 
     name: 'myNewName' 
    }), 

    success: function() { 
     window.location('/character/show/'+$("a#identity-edit").attr("data-id")); 
    }, 
    failure: function(msg) { 
     alert("Fail : " + msg); 
    }, 
    error: function(xhr, status, text) { 
     alert(text); 
     var response = jQuery.parseJSON(xhr, responseText); 
     alert(response.error); 
    } 
}); 

而且,你確定你想要POST?如果您使用Sails藍圖,則更新使用PUT完成。