0

我有以下ajax。每当指定的输入元素发生变化时,该函数将尝试重新计算总数。

$('[name^=quantities]').change(function() {
      calculate();
});
function collectFormData(fields) {
    var data = {};
    for (var i = 0; i < fields.length; i++) {
        var $item = $(fields[i]);
        data[$item.attr('name')] = $item.val();
    }
    return data;
}

function calculate(){
    var $form = $('#purchase-form');
    var $inputs = $form.find('[name]');
    var data = collectFormData($inputs);
    $.ajax({
        url: '${validateUrl}',
        type: 'POST',
        data: data,
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            alert(response.status);
        },
        error: function () {
            alert("error");
        }
    });
}

HTML:

<form id="purchase-form" action="/MyNewApp/purchase" method="post">
...
...
<input id="quantities[0]_id" name="quantities[0]" type="number">
<input id="quantities[1]_id" name="quantities[1]" type="number">
</form>

我在春天的处理程序

@RequestMapping(value = "/purchaseValidation.json", method = RequestMethod.POST)
    @ResponseBody
    public ValidationResponse validate(
            @ModelAttribute(value = "form") @Valid PurchaseForm form,
            BindingResult result, Locale locale) {
        ValidationResponse res = new ValidationResponse();
        // value of form.getQuantities.get(0) == 0
        // value of form.getQuantities.get(1) == 0
        return res;
    }

采购表格.java

public class PurchaseForm {

    private List<Item> itemList;

    private List<Integer> quantities;

    private boolean starterPackageRequired;

    public PurchaseForm() {

    }
        ...
        ...
}

在我的 ajax 帖子中,我可以看到数量的值是 2 和 0,但是在我的 spring 处理程序上,这两个值都是 0。任何指针可能导致这种情况?

4

2 回答 2

0

将输入元素的名称从name="quantities[0]"和更改name="quantities[1]"name="quantities"

注意:出于性能原因,还要将选择器$('[name^=quantities]')更改为$('input[name^=quantities]')

于 2013-03-19T04:14:35.300 回答
0

我通过将 ajax 调用函数更改为此来修复它:

 $.post('${validateUrl}', data, function(response) {
        $('#ajaxResult').text(response);
    }, 'json');

$.post我想和之间一定有一些区别$.ajax

于 2013-03-19T05:47:19.833 回答