2011-08-04 77 views
0

以下一段mootools代碼沒有任何問題。我想用onsubmit事件重寫它,而不是像第二個代碼塊那樣重寫它。謝謝。Mootools Form onsubmit without domready

<html> 
<head> 
<title>Simplest Form Ajax</title> 
<script type="text/javascript" src="../mootools/mootools-core-1.3.2fc.js"></script> 
    <script type="text/javascript"> 
    window.addEvent('domready', function() { 
     $('myForm').addEvent('submit', function(e) { 
      e.stop(); 
      this.set('send', { 
       onComplete: function(response) { 
        $('log_res').set('html', response); 
       } 
      }); 
      this.send(); 
     }); 
    });  
</script> 
</head> 
<body> 
<h3>Send a Form with Ajax</h3> 
<form id="myForm" action="ajaxRes.php" method="post"> 
    <div> 
     <p>Enter something: 
      <input type="text" name="something" value="John" /> 
      <input type="submit" /> 
     </p> 
    </div> 
</form></br></br> 
<h3>Ajax Response</h3> 
<div id="log_res"></div> 
</body> 
</html> 

未完成代碼:

<html> 
<head> 
<title>Simplest Form Ajax</title> 
<script type="text/javascript" src="../mootools/mootools-core-1.3.2fc.js"></script> 
    <script type="text/javascript"> 
    function loadMe() { 
      ... 
    }); 
</script> 
</head> 
<body> 
<h3>Send a Form with Ajax</h3> 
<form id="myForm" action="ajaxRes.php" onsubmit="loadMe()" method="post"> 
    <div> 
     <p>Enter something: 
      <input type="text" name="something" value="John" /> 
      <input type="submit" /> 
     </p> 
    </div> 
</form></br></br> 
<h3>Ajax Response</h3> 
<div id="log_res"></div> 
</body> 
</html> 
+0

爲什麼你更喜歡第二塊?第一個被認爲是優雅的解決方案。如果它傷害你的眼睛,將它移動到外部文件:) –

回答

0

可以使用表單的動作屬性使用JavaScript:前綴(http://jsfiddle.net/mT7WB/

這裏可能是一個可能的實現(代碼未測試):

<html> 
<head> 
<title>Simplest Form Ajax</title> 
<script type="text/javascript" src="../mootools/mootools-core-1.3.2fc.js"></script> 
    <script type="text/javascript"> 
    function submit() { 
      var obj = {}; 
      ["something","somethingElse"].each(function(n) { 
       obj[n] = ("myForm").getElement("input[name="+n+"]").get("value"); 
      }); 
      new Request.HTML({"url" : "ajaxRes.php"}).addEvent("success", function(resp) {$("log_res").adopt(resp);}).post(obj); 
    }); 
</script> 
</head> 
<body> 
<h3>Send a Form with Ajax</h3> 
<form id="myForm" action="javascript:submit()" method="post"> 
    <div> 
     <p>Enter something: 
      <input type="text" name="something" value="John" /> 
      <input type="text" name="somethingElse" value="John" /> 
      <input type="submit" /> 
     </p> 
    </div> 
</form></br></br> 
<h3>Ajax Response</h3> 
<div id="log_res"></div> 
</body> 
</html> 

乾杯!