最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamically append data to form post - Stack Overflow

programmeradmin1浏览0评论

working with an html form, with a "post" method, is there a way to instruct the browser to dynamically add data (once client posts the form) to a post WITHOUT it being in the form of an input elements' name value pairs? Could you use javascript/jquery/ajax to just say, when this form gets posted, append some characters?

working with an html form, with a "post" method, is there a way to instruct the browser to dynamically add data (once client posts the form) to a post WITHOUT it being in the form of an input elements' name value pairs? Could you use javascript/jquery/ajax to just say, when this form gets posted, append some characters?

Share Improve this question asked Dec 9, 2011 at 8:00 Sam AdamshSam Adamsh 3,3919 gold badges34 silver badges54 bronze badges 2
  • 1 what do you mean by 'characters', that is not a name value pair? Do you want to suffix an existing name value pair? Or do you want to add another name value pair, only not by means of appending another input element to the DOM? – David Hedlund Commented Dec 9, 2011 at 8:04
  • i want to know how to add name value pair without appending another input element, thanks for the clarification – Sam Adamsh Commented Dec 9, 2011 at 8:31
Add a ment  | 

3 Answers 3

Reset to default 3
<form id="form1" onsubmit="sbmForm1();return false;">
<input type="text" name="var1" value="value1" />
<input type="text" name="var2" value="value3" />
<input type="submit" name="sbm-btn" value="send" />
</form>

In javascript function sbmForm1 you can add parameter and send them via ajax:

    $.ajax({
        url: 'http://www.yoururl./script.php',
        type: 'POST',
        cache: false,
        data: $('#form1').serialize() + '&yournewvar=yournewvalue',
        success: function(msg) {
            location.reload();
        }
    });

You need jquery to do this request!

You can Use XMLHttpRequest Javascript object to do this. Go to mozilla developer docs to see the api of this object.

You can also use serializeArray(), which allows you to add data to a JSON structure:

var form = $('#form1');

form = form.serializeArray();

form = form.concat([
    {name: "customer_id", value: window.username},
    {name: "post_action", value: "Update Information"}
]);

$.post('/change-user-details', form, function(d) {
    if (d.error) {
        alert("There was a problem updating your user details")
    } 
});
发布评论

评论列表(0)

  1. 暂无评论