jQuery post request (not AJAX)

前端 未结 5 1906
醉酒成梦
醉酒成梦 2020-11-29 21:54

In an ASP.NET MVC app I use jQuery for posting data on button-click:


....
$.post(\'<%=         


        
5条回答
  •  执笔经年
    2020-11-29 22:14

    I created a $.form(url[, data[, method = 'POST']]) function which creates a hidden form, populates it with the specified data and attaches it to the . Here are some examples:

    $.form('/index')
    
    
    $.form('/new', { title: 'Hello World', body: 'Foo Bar' })
    
    
    $.form('/info', { userIds: [1, 2, 3, 4] }, 'GET')
    
    
    $.form('/profile', { sender: { first: 'John', last: 'Smith', postIds: null },
                         receiver: { first: 'Foo', last: 'Bar', postIds: [1, 2] } })
    
    

    With jQuery's .submit() method you can create and submit a form with a simple expression:

    $.form('http://stackoverflow.com/search', { q: '[ajax]' }, 'GET').submit();
    

    Here's the function definition:

    jQuery(function($) { $.extend({
        form: function(url, data, method) {
            if (method == null) method = 'POST';
            if (data == null) data = {};
    
            var form = $('
    ').attr({ method: method, action: url }).css({ display: 'none' }); var addData = function(name, data) { if ($.isArray(data)) { for (var i = 0; i < data.length; i++) { var value = data[i]; addData(name + '[]', value); } } else if (typeof data === 'object') { for (var key in data) { if (data.hasOwnProperty(key)) { addData(name + '[' + key + ']', data[key]); } } } else if (data != null) { form.append($('').attr({ type: 'hidden', name: String(name), value: String(data) })); } }; for (var key in data) { if (data.hasOwnProperty(key)) { addData(key, data[key]); } } return form.appendTo('body'); } }); });

提交回复
热议问题