简体   繁体   English

Spring MVC和Ajax验证

[英]Spring MVC and Ajax Validation

I have the following ajax. 我有以下ajax。 Whenever the specified input element changes, the function will try to recalculate the total. 每当指定的输入元素更改时,该函数将尝试重新计算总数。

$('[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: 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>

My handler in Spring 我的春季经理

@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;
    }

PurchaseForm.java PurchaseForm.java

public class PurchaseForm {

    private List<Item> itemList;

    private List<Integer> quantities;

    private boolean starterPackageRequired;

    public PurchaseForm() {

    }
        ...
        ...
}

During my ajax post I can see the value of quantities are 2 and 0, however on my spring handler both values are 0. Any pointer what might cause this ? 在我的Ajax发布期间,我可以看到数量的值是2和0,但是在我的spring handler上,这两个值都是0。任何指针可能导致此情况?

Change the name of the input elements from name="quantities[0]" and name="quantities[1]" to name="quantities" . 将输入元素的name="quantities[0]"name="quantities[0]"name="quantities[1]"更改为name="quantities"

Note: Also change the selector $('[name^=quantities]') to $('input[name^=quantities]') for performance reasons 注意:出于性能原因,还将选择器$('[name^=quantities]')更改$('input[name^=quantities]')

I fix it by changing the ajax call function to this: 我通过将ajax调用函数更改为此来修复它:

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

I guess there must be some difference between $.post and $.ajax 我猜$.post$.ajax之间一定有一些区别

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM