2016-10-03 64 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。我正在查 –