简体   繁体   English

发布带有ajax和未知表单字段的表单

[英]Posting a form with ajax and unknown form fields

Using jQuery its quite simple to post data to a server using ajax. 使用jQuery,使用ajax将数据发布到服务器非常简单。

Is there a jquery function to post a form using the form name and receive the status from the server like other traditional ajax post calls. 是否有一个jQuery函数使用表单名称发布表单并像其他传统的ajax发布调用一样从服务器接收状态。

But what if we simply wanted to post a form by its name or ID and when I have an unknown set of form fields. 但是,如果我们只是想按名称或ID来发布表单,并且表单集字段未知,该怎么办。

What Id like to do is fetch the form on the page, and just submit the form and current data 我想做的就是在页面上获取表单,然后提交表单和当前数据

See example code: 请参阅示例代码:

HTML 的HTML

<form name='myform'>
    <input type='hidden' value='1' name='somefield'>
    <input type='hidden' value='2' name='somefield2'>
    <input type='hidden' value='3' name='somefield3'>

</form>

<a href='#' class='postform' form_name='myform'>post using ajax</a>

JS JS

$('.postform').click( function() {

    form_name = $(this).attr('form_name');

    postto = 'http://mysite-endpoint.com/api';

    form = $(form_name).submit(postto).done(function(data)
    {
        var ndata = jQuery.parseJSON(data);

        if(ndata.status=='error')
        {
            //display error
        }

        if(ndata.status=='success')
        {
            //looks good
        }
    });

    return false;
});

You can use jQuery $.serialize() to tokenize the form and submit based on the form attributes. 您可以使用jQuery $ .serialize()标记表单,并根据表单属性进行提交。 Something like this: 像这样:

$('#someform').submit(function(ev) {
    ev.preventDefault();
    var $form = $(this);

    $.ajax($form.attr('action'), {
        type: $form.attr('method') || 'get',
        data: $form.serialize(),
    }).then(function() {
        alert('success');
    }, function() {
        alert('error');
    });
});

Here's a fiddle. 这是一个小提琴。

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

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