【问题标题】:how to send an email to admin by running a php file through jQuery如何通过 jQuery 运行 php 文件向管理员发送电子邮件
【发布时间】:2025-12-22 20:30:07
【问题描述】:

当一个用户通过 from 提出请求时,我需要向我的站点管理员发送通知电子邮件。我的代码如下,链接发送邮件的服务器中的 php 文件

$("#modelform").submit(function (event) {
        event.preventDefault();
        $.ajax({
    url: 'send_mail.php',
    success: function(){
         alert('php runing');
         $("#sendRequest").modal("show");
         $("#myModal").modal("toggle");
    }
});

    });

但它没有反应!我的知识很少有人可以指导我实现这一目标吗?我检查了这个question 这是我做错的方式还是我需要链接引导库以外的任何文件?

【问题讨论】:

  • send_mail.php 存在吗?
  • 是的,但没有任何反应!我放了一个错误日志,它重定向到 main.js 文件日志是 Uncaught TypeError: Cannot read property 'offsetWidth' of null
  • "Uncaught TypeError" 可能是由模态引起的。你看到警报了吗?
  • 没有,只能在控制台看到!

标签: javascript php jquery


【解决方案1】:

你可以试试这样的:


HTML:

<textarea id="contactUs"></textarea><div id="button">Send</div>
<div id="response"></div>

jQuery:

$("#button").click(function(){ //when div id="button" is clicked
    var content = $("#contactUs").val(); //get value of textarea id="contactUs"
    $.post('send_mail.php',{content: content}, function(data){ //post data
        $('#response').html(data); //return content of send_mail.php
    });
});

然后是send_mail.php:

<?php 
if(isset($_POST['content']) === true){
    $content = $_POST['content']; //might wanna sanitize if you're storing into db
    $to = "YourEmail@example.com"; //The email sending to
    $subject = "Sent From Contact form"; //The subject of email
    mail($to, $subject, $content, 'From: contact@example.com'); //PHP mail() function
    echo "Sent!"; //This will go to div id="response" on success
} else {
    echo "Error!"; //This will go to div id="response" on error
}
?>

【讨论】:

  • 嗯,所以我有很多字段,所以我需要写怎么写? var content = ("#contactUs").val();var smthing=("#contactUS").val(); $.post('send_mail.php',{content: content,smthing}, function(data){ $('#response').html(data); //会返回send_mail.php的内容 });我是对的还是如果我错了我需要做任何改变对不起,因为我在这里说的知识很少!
  • 您拥有的字段越多,您可以使用var yourVariableName = $("#theIdOfYourField").val(); 获取它们的值,然后您可以通过将它们添加到具有{content:content} 的位置来发布它们。所以它看起来像这样:$.post('send_mail.php', {content:content,postObject:jsVar2,etc:etc}, function(data){... postObject 是您将从 PHP 文件中访问的内容,jsVar2 是您为获取字段值所做的变量
最近更新 更多