2014-09-21 127 views
0

我想創建一個腳本,當有人點擊一個按鈕時,將發送一封電子郵件到我們公司的電子郵件。該html將託管在一個靜態頁面上,並將完成所有客戶端,而php代碼將託管在另一個域中。使用ajax發送數據,然後發送電子郵件

我到目前爲止試過的是。

HTML

<head><title>Report Errors</title> 
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js' type='text/javascript'></script></head> 
<script>$(".c").click(function(){ 
var href = this.href; 
     $.ajax({ 
     url: 'http://example.com/m35.php', 
     type: 'POST', 
     data: { subject: href }, 
     success: function (data) { 
        setTimeout(function(){ 
        $(".container").html(data) 
        }, 1000) 
       } 
     }); 
    }) 
</script> 

<a href="http://link-to-be-sent.example.com" class="c">send</a> 
<div class="container">success</div> 

而且在m35.php文件中的代碼 -

<?php 

$mailTo = "[email protected]"; 
$mailFrom = "[email protected]"; 
$subject = $_POST["subject"]; 
$message = "someone reported the content in subject doubtful."; 


mail($mailTo, $subject, $message, "From: ".$mailFrom); 
?> 

編輯:根據意見,我要澄清的是它甚至不工作的同一域和目錄, 但是這種類型的代碼也在工作,但如何做到這一點,沒有與JavaScript/jquery頁面重新加載。

<form method="post" action="http://example.com/m35.php"> 
<input type="text" name="subject" id="subject" value=""> <input type="submit"> 
</form> 
+1

這是一個CORS的問題,在這裏你可以不將數據發送到使用AJAX不同的域。 – Scimonster 2014-09-21 13:02:14

+1

也許這可能有幫助嗎? https://stackoverflow.com/questions/17318426/cors-cross-domain-ajax-without-jsonp-by-allowing-origin-on-server – parchment 2014-09-21 13:03:25

+0

感謝您的建議@Scimonster,但這甚至不能在同一個域上工作 – Avadhesh18 2014-09-21 13:06:11

回答

2

在呈現dom元素之前附加了Click事件。所以它不會被解僱。 $(".c")a html元素,所以點擊後,它會加載另一個頁面。在這種情況下,ajax請求可能無法到達服務器。爲了防止這種情況的JS代碼應該是$(document).ready()事件並使用return false;從點擊事件阻止頁面加載:

<script> 
$(document).ready(function(){ 
    $(".c").click(function(){ 
     var href = this.href; 
     $.ajax({ 
      url: 'http://example.com/m35.php', 
      type: 'POST', 
      data: { subject: href }, 
      success: function (data) { 
       setTimeout(function(){ 
        $(".container").html(data) 
       }, 1000); 
      } 
     }); 
     return false; // prevent load to another page 
    }); 
}); 
</script> 
+0

謝謝解決,但它仍然沒有發送電子郵件。通過表單提交時,請參閱更新後的問題。 – Avadhesh18 2014-09-21 13:38:50

+0

如果你點擊'a' html元素,它會加載另一個頁面,並且js代碼可能不會被執行。查看我所做的修改。 – py3r3str 2014-09-21 13:42:03

+0

Upvoted。感謝它一切工作。你知道如何在不同的域上運行html和php。 – Avadhesh18 2014-09-21 15:41:55