2011-05-30 51 views
0

幫助,我想獲得一個表單提交 - 阿賈克斯風格。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> 

回答

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> 
+0

您好,我希望這個功能將是該「謝謝「替換了表單......目前這並不是那樣。 – rockit 2011-05-30 09:09:12

+0

你沒有在問題描述中指定。無論如何,如果你試圖用響應文本替換一個id爲「result」的元素,你怎麼能做到這一點?代碼中沒有包含id「result」的元素。 – 2011-05-30 09:17:44