How to use a function as data with jQuery ajax

时间:2018-03-25 20:02:16

标签: javascript jquery ajax

To reduce duplicated script, I created the following plugin, and it works as long as data is left as is.

$.fn.myValid = function(rules, options) {
    this.validate({
        rules: rules.rules,
        messages: rules.messages,
        submitHandler: function(form) {
            var o = Object.assign({},{
                type:'POST',
                url:null,
                data: $(form).serializeArray(),
                dataType: 'json',
                success: function (rsp){
                    //Instead of reloading page, do dynamicly
                    $.unblockUI();
                    alert('record submitted')
                    location.reload();
                },
                error: function (xhr) {
                    $.unblockUI();
                    alert(xhr.responseJSON.message);
                }
                }, options);
            //if (typeof o.data === "function") o.data=o.data(form);
            $.blockUI();
            $.ajax(o);
        }
    });
};

If data needs to be changed, I cannot simply return something like $(form).serializeArray().concat($('#common-inputs').serializeArray(form)) because form is not yet defined, so instead I thought returning a function would work. When ajax is fired, however, data is a function, and not a string, array, or plain object, so data is not sent to the server.

$('#help-form').myValid(validObj.common, {url:'ajax.php','data': function(form){
    console.log('this is never executed);
    return $(form).serializeArray().concat($('#common-inputs').serializeArray(form))
}});

As a workaround, I included o.data=o.data(form); (is commented out in above script) to execute the function to return results, and it works as desired. I expect, however, it is more of a hack, and there is a correct way to do this.

What is the proper way to use a function as data with jQuery ajax?

Will the solution be different for other properties such as url, success, etc?

2 个答案:

答案 0 :(得分:5)

您可以使用 beforeSend 回调来设置数据值:

pr.LM = predict(LM_10[[1]]) is not applicable.

您可以修改网址和成功回调的方式相同:

beforeSend: function( xhr, settings ) {
    this.data = $(form).serialize(); // or settings.data = $(form).serialize();
}, 

Similar question

请注意,这不适用于GET请求,但POST应该可以正常工作。

答案 1 :(得分:2)

你的第一个问题: 使用jQuery ajax将函数用作数据的正确方法是什么?

只要您要在函数调用中返回数据,就可以使用函数创建任何类型的数据。与jquery ajax一样,这将是一个回调函数,您可以在需要时调用它。

# Example

function formData( form ) {
    // do anything
    return form.serialize();
}

var request = $.ajax({
    // set properties
    data: formData.call( context, form );
});

对于其他属性(如网址,成功等),解决方案是否会有所不同?

对于成功回调,使用.done()方法或.fail()方法进行错误

并且网址:

function getFormURL( form ) {
    return form.attr('action');
}

url:getFormURL.call(context,.form);