将数组从jQuery(ajax)发送到PHP

时间:2011-10-30 10:47:11

标签: php jquery

email是一组电子邮件地址。我如何在jQuery中获取数组,然后使用AJAX将数据与class titlemessage一起发送到send.php?

    <input type='text' size='30' class='email' value='testing1@gmail.com' />
    <input type='text' size='30' class='email' value='testing2@gmail.com' />
    <input type='text' size='30' class='email' value='testing3@gmail.com' />
    <input type='text' size='30' class='title' value='testing title' />
    <input type='text' size='30' class='message' value='testing message' />

<script type="text/javascript">
$(function() {
var title = $('.title').val();
var message = $('.message').val();

var dataString = 'title=' + title + '&message=' + message;
$.ajax({
    type: "POST",
    url: "send.php",
    data: dataString,
success:function () {


}

});
});
</script>

send.php

<?php


  $email = $_POST['email'];
  $title = $_POST['title'];
  $message = $_POST['message'];

foreach($email as $value) {

//send email

}
?>

3 个答案:

答案 0 :(得分:1)

这应该这样做:

var data = {
    title: $('.title').val(),
    message: $('.message').val(),
    email: $('.email').map(function(){ return $(this).val(); }).get()
};

$.ajax({
    type: "POST",
    url: "send.php",
    data: data,
    success:function () {

    }
});

data.email将包含一系列电子邮件地址。 jQuery负责正确编码数据。请参阅jQuery.param

答案 1 :(得分:1)

如果您为输入命名,则可以使用Felix King's answer更简单地执行serialize()

<form id="the-form">
    <input type='email' size='30' name="email[]" value='testing1@gmail.com' />
    <input type='email' size='30' name="email[]" value='testing2@gmail.com' />
    <input type='email' size='30' name="email[]" value='testing3@gmail.com' />
    <input type='text' size='30' name='title' value='testing title' />
    <input type='text' size='30' name='message' value='testing message' />
</form>
$.ajax({
    type: "POST",
    url: "send.php",
    data: $("#the-form").serialize(),
    success: function() {

    }
});

答案 2 :(得分:0)

这不会起作用吗?:

var datastring = $('#yourform').serialize();