2016-10-03 66 views
1

我试图发送电子邮件给多人,一旦电子邮件发送成功,然后我通过ajax响应追加消息。下面的代码工作正常如何在处理时在ajax中添加基于php响应的消息?

if(!empty($sendEmails)){ 
    $sendCount = 0; 
    foreach($sendEmails as $mail){ 
     $sent = $this->sendEmail('', $mail, $subject, $data); 
     if($sent != 'Message Sent'){ 
     $response['send_error'][] = 'There is an error with ['.$mail.']'; 
     }else{ 
      $sendCount++; 
     } 
    } 
} 
$response['success'] = 'Email has been sent successfully to '. $sendCount. ' person(s).'; 

阿贾克斯

$.ajax({ 
    type:'POST', 
    url:'post.php', 
    data:formData, 
    dataType:"json", 
    success:function(response){ 
     $(".sndMail").remove(); 
     if(response.success){ 
      $(".sendResponse").prepend('<div class="alert alert-success sndMail"> <strong>Alert! </strong> '+response.success+'</div>'); 
     } 
     if(response.send_error){ 
      for(f=0; f<response.send_error.length; f++) { 
       //alert(response.fileErr[f]); 
       $(".sendResponse").prepend('<div class="alert alert-danger sndMail"> <strong>Alert! </strong> '+response.send_error[f]+'</div>'); 
      } 
     } 
     if(response.error){ 
      for(f=0; f<response.error.length; f++) { 
       //alert(response.fileErr[f]); 
       $(".sendResponse").prepend('<div class="alert alert-danger sndMail"> <strong>Alert! </strong> '+response.error[f]+'</div>'); 
      } 
     }  
    } 
}); 

,但我想使用户查看更多良好的通过将每个邮件发送响应。我想在处理过程中附加每条回复消息,如Response: Email is send to [email protected],一旦发送完所有电子邮件,我将显示已在使用的成功消息。

那么任何人都可以引导我关于这是可能与ajax或不?如果有人指导我,我想感谢。我搜查了它,但我没有找到解决方案。

回答

0

是的,你可以。尝试一些事情是这样的:

$response = array(); 
foreach($sendEmails as $mail){ 
if(mail()) // success 
{ 
    $response[$mail] = ''; // your message 
} 
else   // fail 
{ 
    $response[$mail] = ''; // your message 
} 
} 

echo json_encode($response); 

AJAX:

success:function(response) 
{ 
    var data = JSON.parse(response); 
    // data contains the success or failure message for each email id. 
    // Show the status by wrapping the each email in <li> or <div> by using $.each loop 
} 
+1

我觉得@Mr开发者希望所有的电子邮件被发送之前得到中间结果。 –

+0

@GabrielGlenn完全是 –

+0

在这种情况下,您必须提出多个Ajax请求,这不是一个好主意 –

1

你想要什么是不可能与一个单一的Ajax调用,但它可以多次调用来完成。

想法是使用一个ajax调用来运行该进程,第二个调用来定期轮询进度。

入住这太问题:Multiple Response AJAX request

+0

感谢您分享有用的准则+1。我正在查 –