2013-06-11 43 views
0

林解析使用Ajax PHP与来自数组中的值发送电子邮件数组时有困难。阿贾克斯阵到PHP问题

Ajax代码:

$(document).ready(function(){ 

      $("#submit-button").click(function(){ 

       var countryArray = ['Location Zero', 'Location One', 'Location Two']; 

       dataString = countryArray; 
       var jsonString = JSON.stringify(dataString); 

       $.ajax({ 
         type: "POST", 
         url: "sendmail.php", 
         data: {countries: jsonString}, 
         success: function (msg) { 

          $("#errors").text("Thank you for getting in touch, we will get back to you!"); 

         }, 
         error: function (msg) { 
          $("#errors").text("Error sending email, please try again."); 

          alert("error"); 
         } 
        }); 


}); 

}); 

PHP代码:

<?php 


     $to = "[email protected]"; 
     $countries = json_decode($_POST['countries']); 

     $header = "Content-Type: text/html\r\nReply-To: \r\nFrom: <>"; 
     $subject = "Email from the Lister customer"; 

     $body = @"$countries"; 


     if(mail($to, $subject, $body, $header)) { 
      die("true");  
     } else { 
      die("There was an error sending the email."); 
     } 


?> 

但是,所有我与收到的电子邮件从$countries是单词 “阵列”,而不是价值。

任何人都可以帮忙吗?

+0

'$ countries'是一个数组,因此使用'破灭( “”,$国家);'将其打印为一个字符串。 – Joe

+0

'@“$ countries”'?不要压制错误,也不要使用货物 - 邪教编程... –

+0

谢谢你们,现在所有的工作都完美:) – medzi

回答

0
<?php 


    $to = "[email protected]"; 
    $countries = json_decode($_POST['countries']); 

    $header = "Content-Type: text/html\r\nReply-To: \r\nFrom: <>"; 
    $subject = "Email from the Lister customer"; 

    $body = implode(", ", $countries); 


    if(mail($to, $subject, $body, $header)) { 
     die("true");  
    } else { 
     die("There was an error sending the email."); 
    } 
?> 
+0

太棒了!这样可行!非常感谢你! – medzi

+0

@YogeshSuthar我知道,它不会让我立刻接受它。我得等一会儿。但现在全部完成了:) – medzi

3

$countries是一个数组。如果你想让它在你的$body显示为一个列表,你可以这样做:

$body = implode(', ', $countries); 

也请尽量不要压抑(@)PHP错误,它会导致你在未来更头疼的问题。

0

如果你使用jQuery,请尝试使用.serializeArray()而不是字符串化。

而且,在接收到$ _ POST时[“contries”]变量,你需要它发生内爆。试试这个:

$(document).ready(function(){ 
    $("#submit-button").click(function(){ 
     var countryArray = ['Location Zero', 'Location One', 'Location Two']; 
     $.ajax({ 
      type: "POST", 
      url: "sendmail.php", 
      data: {countries: countryArray.serializeArray()}, 
      success: function (msg) { 
       $("#errors").text("Thank you for getting in touch, we will get back to you!"); 
      }, 
      error: function (msg) { 
       $("#errors").text("Error sending email, please try again."); 
       alert("error"); 
      } 
     }); 
    }); 
}); 

然后在PHP中使用这个正确抓住国家价值观:

implode(', '.$countries);