【问题标题】:How to POST data using the 'save' method of the backbone.js如何使用backbone.js的“保存”方法发布数据
【发布时间】:2015-04-09 18:38:34
【问题描述】:

我正在尝试使用主干“保存”方法保存表单数据。我正在使用 POST http 方法将数据保存到服务器。数据确实保存到服务器,但是在网络控制台中,我看到 POST 状态显示已取消,但成功创建了数据。 这是js:

var account = Backbone.View.extend({
    el: "#account",
    events:{
        'click button#save' : 'saveList'
    },
    render: function(id){
        value = new accountModel([],{id:id});
    },              
    saveList: function(event){  
        var values = $('#form').serializeJSON();        
            value.save(values, {
                success: function(value){
                    console.log(“success”)  
                },
                error: function(err){
                    console.log('sorry, your record was not saved' + err);  
                }
            });
});

html:

<form class="form" id="form">
    <table>
        <tbody>
            <tr>
             <label>name</label>
             <td><input type="text" name="accountName" maxlength="50"/> </td>            
           </tr>
           <tr>
             <label>first</label>
             <td><input type="text" name="first" maxlength="50"/> </td>            
           </tr>
          <tr>
             <label>last</label>
             <td><input type="text" name="last" maxlength="50"/> </td>            
           </tr>
      </tbody>
   </table>
</form>

我在 success() 和 error() 处设置了一个调试器点,它总是出现错误,但仍会发布数据。我在这里做什么,为什么它的行为如此奇怪?有什么想法吗??

【问题讨论】:

  • 错误是什么样的?响应或错误代码是什么?
  • 您还在笨拙地实例化您的帐户模型。 new accountModel([],{id:id}); 初始化模型的正确方法是先使用attributes,然后是optionsattributes 应该是一个对象,而不是数组。我猜您模型中的 url 函数依赖于 this.id ?这不是在模型上存储 ID 的正确方法。它应该在属性中。

标签: jquery backbone.js


【解决方案1】:

这里好像回答了这个问题:jquery $.post() getting canceled

基本上,您需要在 saveList 函数中添加一个 event.preventDefault()(在其他任何内容之前)。

【讨论】:

  • 该答案特定于使用&lt;a&gt; 提交表单时。我不认为这里是这种情况,对吧?
  • 是的。看起来浏览器正在某处取消请求,如果不是在锚标记上,也许是通过按钮提交表单......很难说没有看到更多代码(或 jsfiddle!)。
猜你喜欢
  • 2012-04-06
  • 2013-08-10
  • 2013-02-24
  • 1970-01-01
  • 2013-11-29
  • 2011-12-19
  • 2012-08-25
  • 1970-01-01
  • 2017-08-04
相关资源
最近更新 更多