根据单击的链接更新PHP变量

时间:2013-04-24 08:32:06

标签: php jquery

我使用此循环显示包含用户列表的页面:

foreach ($mytaxonomies as $mytaxonomy) :  setup_postdata($mytaxonomy);
  echo $mytaxonomy->name; // print the name of the user
  echo '<a>Send email</a>';
endforeach;

对象$mytaxonomy包含许多值,例如$mytaxonomy->email

中当前用户的电子邮件

点击链接(发送电子邮件)会显示带有表单的模式叠加层,以便向该用户发送电子邮件。 表单将邮件发送到变量$to中指定的电子邮件地址,但我无法将$mytaxonomy->email分配给该变量(取决于单击的链接)。

我需要像

这样的东西
<?php $to = $mytaxonomies[...]->email; ?>

每当我点击其他用户时,$mytaxonomies[...]->email会发生变化(因为显然每个用户都有不同的电子邮件)。

编辑: $ mytaxonomies是包含所有用户及其信息的数组

print_r($mytaxonomies);

Array
(
    [0] => stdClass Object
        (
            [term_id] => 4
            [name] => John Doe
            [slug] => john-doe
            [email] => johndoe@email.com
            [age] => ...
            [phone] => ...
        )

    [1] => stdClass Object
        (
            [term_id] => 5
            [name] => Jane Doe
            [slug] => jane-doe
            [email] => jdoe77@converge.con
            [age] => ...
            [phone] => ...
        )

    ...
)

2 个答案:

答案 0 :(得分:1)

使用ajax发送电子邮件。或者在另一页中。加载页面后,您无法在页面中设置php变量。

Ajax示例:

$(document).on('click', 'a', function(){
  var data = 'mail=' + $(this).prop('href');
  $.ajax({
    type: 'POST',
    data: data,
    url: 'sendmail.php',
    success: function(){
      alert('mail sent');
    }
  )};
)};

PHP:

<?
foreach ($mytaxonomies as $mytaxonomy) :  setup_postdata($mytaxonomy);
  echo $mytaxonomy->name; // print the name of the user
  echo "<a href='{$mytaxonomy->email}'>Send email</a>";
endforeach;
?>

在sendmail.php中,您可以使用POST获取可变邮件 例如:$to = $_POST["mail"];

HTML表单:

<form id="myform" style="display:none" action="sendmail.php">
 ...
 <input name="to">
 <input name="from">
 ...
</form>

jquery:

$(document).on("click", "a", function(){
  var mail = $(this).prop("href");
  $("#myform").show();
  $('#myform input[name="to"]').val(mail);
});

您将不再需要ajax。表单将发送给sendmail.php。 注意:“......”是表单的其余部分:)

答案 1 :(得分:-1)

!!!!!不要相信来自客户端的任何价值

<?
foreach ($mytaxonomies as $mytaxonomy) :  setup_postdata($mytaxonomy);
  echo $mytaxonomy->name; // print the name of the user
  echo "<a href='send_mail.php?mail={$mytaxonomy->email}'>Send email</a>";
endforeach;
?>

send_mail.php

<?
$mail = $_GET['mail'];
mail($mail, 'My Subject', 'message');
?>

更新&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; &GT;&GT;&GT;&GT;&GT;&GT;&GT;&GT;&GT;

<?
foreach ($mytaxonomies as $mytaxonomy) :  setup_postdata($mytaxonomy);?>
<form  action="send_mail.php" method="post">
<? echo $mytaxonomy->name;?> 

<input type="hidden" name="mail" value="<?echo $mytaxonomy->email?>">
    <input type="submit" value="Send">
</form>
  <? endforeach;?>

send_mail.php

<?
//just for demo send mail function, dont copy and use
$mail = $_POST['mail'];
mail($mail, 'My Subject', 'message');
?>