2010-12-09 65 views
1

我已经做了一个类来处理加载和提交一个html表单。见下面使用mootools提交表单

ND.Form = new Class({ 
    //--- Implements options og events. 
    Implements: [Options, Events], 

    //--- Options. 
    options: { 
     url: '', 
     injectTo: '' 
    }, 

    //--- Initialize the class. 
    initialize: function (panel, options) { 
     //--- Set options 
     this.setOptions(options); 
     this.panel = panel; 
     this.loadForm(); 
    }, 

    loadForm: function() { 
     var req = new Request.HTML({ 
      url: this.options.url, 
      method: 'get', 
      onSuccess: function (html) { 
       $(this.options.injectTo).empty(); 
       $(this.options.injectTo).adopt(html); 
       var formId = $(this.options.injectTo).getFirst('form').get('id'); 
       $(formId).addEvent('submit', function (e) { 
        e.stop(); 
        this.submitForm(formId); 
       } .bind(this)); 
      } .bind(this) 
     }).send(); 
    }, 

    submitForm: function (formId) { 
     $(formId).set('send', { 
      onSuccess: function (resp) { 
       this.panel.loadContent(); 
       if (resp != null) { 
        $('lbl_error').empty(); 
        $('lbl_error').setStyles({ 'display': 'block', 'color': 'red' }).set('html', resp); 
       } 
      }.bind(this), 

      onFailure: function (resp) { 
       if (resp != null) { 
        $('lbl_error').empty(); 
        $('lbl_error').setStyles({ 'display': 'block', 'color': 'red' }).set('html', resp); 
       } 
      } 
     }); 
     $(formId).send(); 
    } 
}); 

代码当我按下保存按钮比1多这一切工作得很好,exept的“this.panel.loadContent();”在“submitForm:function(formId)”中触发了相同的x次按钮次数,我该如何防止这种情况?

/马丁

回答

4

从MooTools的1.3启动 “设置( '发送')” 又增加了一个事件。 所以你需要写:

$('myForm').set('send', { 
    onSuccess: function (html) {}, 
    onFailure: function(xhr){} 
}).addEvent('submit', function(e){ 
    e.stop(); 
    this.send(); 
}); 

代替:

$('myForm').addEvent('submit', function(e){ 
    e.stop(); 
    this.set('send', { 
     onSuccess: function (html) {}, 
     onFailure: function(xhr){} 
    }); 
}).send(); 

然后请求将被一次,每次当你处理形式发送。

4
Basically we need to do three things: 
  1. 监听提交按钮的“点击”事件。
  2. 停止提交表单。
  3. 发送使用表单$(formElement)。发送()

一个解决方案可以是这个样子:

$('submit').addEvent('click', function(evt){ 
    // Stops the submission of the form. 
    new Event(evt).stop(); 

    // Sends the form to the action path, 
    // which is 'script.php' 
    $('myForm').send(); 
    }); 
+0

那么,我的“this.panel.loadContent();”当我尝试你的建议时仍然会多次发射。第一次我点击按钮加载一次,第二次按下按钮加载两次等。 – 2010-12-09 10:36:06

0

我已经使用了request.send()方法,但是试图找到一种方法来复制用户敲击表单提交按钮的操作,但同时也允许预先执行一些JavaScript逻辑。我没有找到任何具体解决这个问题的讨论。我发现的答案是使用form.submit()方法。