-1

我想将数据推送到一个对象中,以便通过 ajax 发布动态数据。

这是我的非工作代码:

$j(document).ready(function() {
        var data = {
            test: 'test'
        }

        $j('.fancyajax').bind('click', function () {
                var myclass = '.' + $(this).attr("id");
                $j(myclass).each(function() {
                        data.push({$j(this).attr("name") : $j(this).val()});
                });
        });
        $j('.fancyajax').fancybox({
                ajax: {
                    type: "POST",
                    data: data
                }
        });
});
4

4 回答 4

3

Array.push()适用于数组 - 对于哈希,您可以这样做:

data[{$j(this).attr("name")] = $j(this).val();
于 2013-05-16T12:33:25.700 回答
2

试试这个:

$j('.fancyajax').bind('click', function () {
    var myclass = '.' + $(this).attr("id");
    $j(myclass).each(function () {
        data[$j(this).attr("name")] = $j(this).val();
    });
});

为了向 javascript对象添加一些数据,您需要执行以下操作:

data['new variable name'] = 'new variable';
于 2013-05-16T12:33:32.197 回答
1

Push if for array,但 data 是一个对象,所以这应该工作:

$j(myclass).each(function() {
                        data[$j(this).attr("name")]  = $j(this).val();
                });
于 2013-05-16T12:34:19.550 回答
1

将您的代码更改为;

data[$j(this).attr("name")]  = $j(this).val();
于 2013-05-16T12:34:54.963 回答