通过jQuery命令提交表单数据 [英] Submitting form data through a jQuery command

查看:75
本文介绍了通过jQuery命令提交表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个MVC项目,并且正在创建一组不同的提交按钮,每个按钮在提交时将不同的值传递给控制器​​.

I have an MVC project I'm working on, and am creating a set of different submit buttons, each which pass a different value to the controller on submission.

在当前代码中,我先调用了commit函数,首先创建隐藏的输入元素以传递所需的数据,如下所示:

In my current code, I have the call to the submit function first create hidden input elements to pass the data I want, something like this:

    $('#btnCreate').live('click', function () {
    $('#formIndex').submit(function (event) {
        $('#actions').append('<input type="hidden" name="objectId" value="' + $('input[name="objectList"]').val() + '" />');
        $('#actions').append('<input type="hidden" name="choice" value="create" />');
    });
});

我想知道是否可以像在$ .get,$.post和$ .ajax函数中那样,将那些隐藏的输入的值作为一组参数传递给Submit调用.我已经尝试过,但似乎还没有找到正确的公式.

I'm wondering if I can just pass the values of those hidden inputs as a set of parameters in the submit call, like you can do with the $.get, $.post, and $.ajax functions. I've experimented but haven't seemed to hit on the right formula yet.

感谢您的帮助!

推荐答案

我认为通过添加隐藏的输入参数可以使您处于正确的轨道.我不知道将数据附加到您的非ajax表单提交中的任何其他方法.

I think you are on the right track by adding hidden input parameters. I don't know of any other way to append data to your non-ajax form submit.

您可能想对代码进行一些更改:

You might want to change a few things about your code though:

  1. 使用jquery构建隐藏的输入(如此处所示在SO上)

var input = $("<input>").attr("type", "hidden").attr("name", "mydata").val("bla"); $('#form1').append($(input));

为获得更好的性能,请使用proxy()而不是live().性能的提高确实取决于您的DOM的深度.但是,委托支持在实时不支持的情况下进行链接. (在jQuery 1.7中,所有这些问题都可以通过on()方法解决……):

For better performance, use delegate() instead of live(). The performance benefit really depends on how deep your DOM is. However, delegate supports chaining where live does not. (In jquery 1.7, all these problems go away with the on() method...):

$('body').delegate('#btnCreate', 'click', function () { ... });

请注意,除了将body用作容器元素之外,还可以在包装了btnCreate元素的DOM中使用较低的内容.

Note that instead of using body as the container element, you could instead use something lower in the DOM which wraps your btnCreate element.

这篇关于通过jQuery命令提交表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆