使用SailsJS和MongoDB进行Ajax更新

时间:2014-03-01 20:07:55

标签: jquery ajax mongodb sails.js

我正处于使用航线的sailsJS的开头。

我有一个关于如何通过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);
        }
    });  

不幸的是,这个代码被“错误”处理程序捕获,文本为空...

你能解释一下我的错误吗?

先谢谢,

西里尔

1 个答案:

答案 0 :(得分: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完成更新。