3

给定以下形式:

<form class="email-form" action="" method="PUT" data-remote="true" data-method="put">
  <ul>
    <li>
      <label for="sEmail1">
        <input type="text" id="sEmail1" name="emails[]" value="d@google.com"
               placeholder="">
      </label>
    </li>
    <li>
      <label for="sEmail2">
        <input type="text" id="sEmail2" name="emails[]" value="d2@google.com"
               placeholder="">
      </label>
    </li>
    <li>
      <label for="sEmail3">
        <input type="text" id="sEmail3" name="emails[]" value="d3@google.com"
               placeholder="">
      </label>
    </li>
  </ul>
  <button type="submit">Continue</button>
</form>

如何使用查询来获取完整的电子邮件列表并将其发布到 rails 如下:

Parameters: {"emails"=>{"list"=>["d@google.com", "d2@google.com","d2@google.com"]}}

我有以下内容:

    $.ajax({
        type: 'POST',
        url: '/send_invites',
        data: {
            emails : {
                list : $('.email-form').serialize()
            },
            _method : 'PUT'
        },
        success : function() {
        }
    });
4

3 回答 3

0

尝试这个:

emails = new Object();
emails.list = [];
i = 0;

$("input[name^='email']").each(function(){
   if(i < 3) {
    emails.list[i] = $(this).val();
    i++
  }

})

alert(JSON.stringify(emails));  

或者:

parameters = new Object();
parameters.emails = new Object()
parameters.emails.list= [];
i = 0;

$("input[name^='email']").each(function(){
   if(i < 3) {
    parameters.emails.list[i] = $(this).val();
    i++
  }

})

alert(JSON.stringify(parameters));   

http://jsfiddle.net/jgjpD/1/

于 2012-04-20T23:05:46.010 回答
0

这是通过扩展 jQuery 并添加serializeObject方法来序列化表单的快速方法。

$(function() {

    //form to object
    $.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    //test it out
    $('form').on('submit', function() {
        var serialized = $(this).serializeObject();

        console.log(serialized);
        console.log(JSON.stringify(serialized));

        return false;
    });

});​
于 2012-04-20T23:15:41.230 回答
0

这是一种方法

var listval = [];
$("input['name=emails\[\]']").each(function() {
    listval.push($(this).val());
}
于 2012-04-20T23:17:58.663 回答