开发者

Submitting form data through a jQuery command

开发者 https://www.devze.com 2023-04-09 16:58 出处:网络
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.

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.

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" />');
    });
});

I'm wondering if I can just pass the values of those hidden inputs as a set of parameters in the submit call, l开发者_如何学编程ike you can do with the $.get, $.post, and $.ajax functions. I've experimented but haven't seemed to hit on the right formula yet.

Thanks for your help!


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. Build your hidden inputs using jquery (as seen here on SO)

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

  2. 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 () { ... });

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


If you have to just submit data in the form to the backend, you can use serialize() function of jquery.

Usage:

      $('form').submit(function() {
         var yourdata = $(this).serialize();
        $.ajax({
                type: "POST",
                 url: "check.php",
                data: yourdata,
             success: function(msg){
                      alert( "Data Saved: " + msg );
               }
           });
      });
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号