动态附加数据以形成帖子

时间:2011-12-09 08:00:41

标签: javascript forms http post dynamic

使用html表单,使用“post”方法,有没有办法指示浏览器动态添加数据(一旦客户端发布表单)到帖子,而不是以输入元素的名称形式价值对?你可以使用javascript / jquery / ajax来说,当这个表单发布时,附加一些字符吗?

3 个答案:

答案 0 :(得分: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>

在javascript函数sbmForm1中,您可以添加参数并通过ajax发送它们:

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

你需要jquery来做这个请求!

答案 1 :(得分:1)

您可以使用XMLHttpRequest Javascript对象来执行此操作。转到mozilla开发人员文档以查看此对象的API。

答案 2 :(得分:0)

您还可以使用serializeArray(),它允许您将数据添加到JSON结构:

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