Ajax表单提交,如何使其工作

时间:2011-05-30 08:28:21

标签: ajax jquery

帮助,我正在尝试提交表单 - ajax样式。

基本上,我希望能够将表单“提交”到另一个页面,而无需将用户重定向到第二页。理想情况下,它会在表单页面上显示某种“成功”或“失败”消息。

以下代码无效。我不确定问题是什么。

我通过发布并将用户重定向到页面来测试我的process.php,它运行完美。有关如何使用ajax工作的任何建议? (我正在使用jquery)

<script>
    $(function() { // wait for the DOM to be ready
    $('#personal_email').submit(function() { // bind function to submit event of form
       $.ajax({
          type: $(this).attr('method'), // get type of request from 'method'
          url: $(this).attr('action'), // get url of request from 'action'
          data: $(this).serialize(), // serialize the form's data
          success: function(responseText) {
              // if everything goes well, update the div with the response
              $('#result').html(responseText);
          }
      });
    return false; // important: prevent the form from submitting
    });
   });
</script>

...

<form  name="personal_email" id="personal_email" action="proccess.php" method="post">
 <fieldset>
     <input type="text" id="newsletteremail" name="newsletteremail" value="my email address" onfocus="if(this.value=='my email address')this.value=''"/>
     <input type="submit" value="Subscribe" />
   </p>
 </fieldset>
</form>

1 个答案:

答案 0 :(得分:0)

以下适用于我:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" ></script>
<script type="text/javascript">
    $(document).ready(function() { // wait for the DOM to be ready
    $('#personal_email').submit(function() { // bind function to submit event of form
       $.ajax({
          type: $(this).attr('method'), // get type of request from 'method'
          url: $(this).attr('action'), // get url of request from 'action'
          data: $(this).serialize(), // serialize the form's data
          success: function(responseText) {
              // if everything goes well, update the div with the response
              $('#result').html(responseText);
          }
      });
    return false; // important: prevent the form from submitting
    });
   });
</script>
</head>
<body>
<div id="result"></div>
<form  name="personal_email" id="personal_email" action="process.php" method="post">
 <fieldset>
     <input type="text" id="newsletteremail" name="newsletteremail" value="my email address" onfocus="if(this.value=='my email address')this.value=''"/>
     <input type="submit" value="Subscribe" />
   </p>
 </fieldset>
</form>
</body>
</html>