【问题标题】:Ajax update with SailsJS and MongoDBSailsJS 和 MongoDB 的 Ajax 更新
【发布时间】:2014-03-01 20:07:54
【问题描述】:

我的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);
        }
    });  

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

你能解释一下有什么问题吗?

提前致谢,

西里尔

【问题讨论】:

  • 问题是你可能有一个服务器端错误,这不是服务器代码。您需要在问题中显示该部分。
  • 对不起,我不明白你的回答
  • 这不是答案,而是评论。您的问题 only 显示您的客户端代码,您发布到服务器上的端点。我们需要看看那里发生了什么。
  • 我明白,但我没有任何其他代码,因为我想使用sails 的REST API,它可以通过URL CRUD 像/:controller/update/:id?parameters ...我不明白的是,如果我启动此代码,我会出现错误状态,但如果我重新加载页面(使用 F5),数据会正确存储在 mongodb 中并正确显示在我的页面中......跨度>
  • 不知何故我就知道你会这么说。你能用你期望的数据达到那个 REST 点吗?看起来您正在将一个对象传递给data,以便 应该 没问题。谷歌“curl JSON”看看如何测试。

标签: jquery ajax mongodb sails.js


【解决方案1】:

当通过 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 完成更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多