JavaScript 事件,与 PHP 混合


JavaScript events, mixed with PHP?

我想出的一个想法遇到了一个巨大的错误。所以我正在做一个项目,在我的主网站上,我们需要建立一个正在处理的页面,yadayda,但我想添加让用户向我们发送电子邮件的功能,但在我们收到该数据后,将显示一个弹出对话框。但这并不像我想要的那样工作。

所以我需要帮助的,实际上是PHP和JavaScript事件,以使其确认消息和电子邮件已发送,然后显示对话框。有谁知道如何做到这一点?或者至少如何在用户执行某些操作后显示对话框,例如输入信息而不是仅单击按钮?如果有人能帮忙,我将不胜感激!

如果使用 jQuery,则可以对服务器端脚本进行 AJAX 调用,并使用成功回调在客户端启动对话框。

$.ajax({
  url: 'ajax/test.php',
  data: { name: "WeLikeThePandaz", email: "panda@gmail.com" },
  success: function(response) {
    if (response.status == "OK"){
      // Show dialog 
    }else{
      // Let the user know there were errors
      alert(response.error);
    }
  }
},'json');

以下是使用 $.ajax 方法的相关文档 -

http://api.jquery.com/jQuery.ajax/


然后,您的服务器端 PHP 代码 ajax/test.php 可以破译发送的数据并组装一个要返回给 jQuery 的 json 对象 -

<?php
$err= '';
$name = sanitizeString($_POST['name']);
$email = sanitizeString($_POST['email']);
// note the sanitization of the strings before we insert them - always make sure
// to sanitize your data before insertion into your database.
// Insert data into database.
$result = mysql_query('INSERT INTO `user_table` VALUES...');
if (!$result) {
  $status = "FAIL";
  $err = mysql_error();
}else{
  $status = "OK";
} 
echo json_encode(array('error'=>$err,'status'=>$status)); // send the response
exit();
?>