2013-06-11 44 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);