0

如果我有这样的动态元素:http: //jsfiddle.net/kfm5b/2/

<select name="roomFac1" id="roomFac1">
  <option selected="selected">Any</option>
</select>
<input type="button" value="Add" class="pmbtn" id="addFac"/>
<input type="button" value="Remove" class="pmbtn" id="removeFac"/>

$(document).ready(function(){
    $('#addFac').click(function(){
        var $objs = $('select[name*=roomFac]');
        var n = $objs.size() + 1;
        var $obj = $objs.first().clone();
        $obj.attr('name', 'roomFac'+n).attr('id', 'roomFac'+n);
        $obj.appendTo($('body'));
    });
    $('#removeFac').click(function(){
        var $objs = $('select[name*=roomFac]');
        if($objs.size() > 1){
           $objs.last().remove();
        }
    });
});

一旦用户单击提交按钮,我将如何获取其输出以用于 AJAX 提交,例如

$("#submit").click(function () {
...
...
var dataString = ....; // how I would I implement the dynamically created elements here s I don't know the size
...
...
$.ajax({
    type: "POST",
    url: "process.php",
    data: dataString,
    cache: false,
    success: function (html) {
        $('#search_room').html(html);
    }
});

其次,我会在处理处理的 PHP 文档中放入什么?

4

2 回答 2

0

我猜你正在尝试做这样的事情:

$("#submit").on('click', function(e) {
    e.preventDefault();
    var dataString = $.map($('[id^="roomFac"]'), function(val, i) {
       return {val.name : val.value}; //return name and value of elements
    });

    $.ajax({
        type: "POST",
        url: "process.php",
        data: dataString,
        success: function (html) {
            $('#search_room').html(html);
        }
    });
});
于 2013-02-17T06:11:36.493 回答
0

考虑到您需要将所有选定元素的值放在dataString.

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

    var dataString = "";

        $('select[name*=roomFac]').each(function(){
            dataString+=$(this).val();
            dataString+=",";
        });

        $.ajax({
            type: "POST",
            url: "process.php",
            data: dataString.substring(0, dataString.length - 1);,
            cache: false,
            success: function (html) {
                $('#search_room').html(html);
            }
        });
    });

一边php

    $dataFromClient = $_POST['data'];
    $dataFromClient = explode(',',$dataFromClient);

//now $dataFromClient  will be an array that contains all the values.
于 2013-02-17T06:16:21.203 回答