Modify POST vars before post, using jQuery

前端 未结 8 669
醉话见心
醉话见心 2020-12-29 18:34

I have a form, and a submit handler in jQuery.

When the user submits the form, I want to modify (add) some parameters to the POST request, before it is despatched fr

相关标签:
8条回答
  • 2020-12-29 18:43

    I don't think you can modify the POST vars that way. When a submit handler runs there's no hash of the form data that really exists that you can add to or modify. I think you're right - your only options to $.post() yourself (which I'd recommend) or to append hidden inputs to the form (has the overhead of DOM modification which you don't really need).

    0 讨论(0)
  • 2020-12-29 18:49
    $('#myForm').submit(function() {
      $.each(this, function (i, element) {
        console.log("element name " + element.name + ", element val: " + element.value);
        if(element.name="thisThingInParticular")
          element.value = "myNewValueForThisElementInParticular";
        )
    
      }
    });
    
    0 讨论(0)
  • 2020-12-29 18:51

    Use the submit() function on the form to create a callback. If the function returns true, the form will be submitted; if false, the form will not post.

    $('#theForm').submit(function() {
        $("#field1").val(newValue1);
        $("#field2").val(newValue2);
        $(this).append(newFormField);
        return true;
    });

    etc.

    0 讨论(0)
  • 2020-12-29 18:53

    I have been working on this question for one day, and I come up with a good solution:

    you could use Jquery .clone() to create a copy of the form you want to submit. Then you could do the modifications on the copy, and finally submit the copy.

    0 讨论(0)
  • 2020-12-29 18:55
    $("#frm").submit(function (e) {
        e.preventDefault();
        form = document.getElementById("frm"); //$("#frm")
    
        $.each(form.elements, function (i, el) {
            el.name = your_new_name;
            el.value = your_new_value;
            //... //el.type, el.id ...
        });
    
        form.submit();
    
        return true;
    });
    
    0 讨论(0)
  • 2020-12-29 19:01

    You can hook the click event of the submit button and do your processing there. For the key/value pairs you might try a hidden form element.

    0 讨论(0)
提交回复
热议问题