---
title: "构造隐藏form提交数据"
author: "iwelcomeyou"
date: "2014-09-14T16:16:45Z"
tags: []
categories: ["Web前端"]
slug: "form"
draft: false
lastmod: "2014-09-12T20:53:14Z"
id: 2115960
url: "https://iwelcomeyou.iteye.com/blog/2115960"
---

```
JQuery构造一个form对象,然后form.submit();就等于是普通form表单向后台提交了! 
    //创建一个form对象
    var form = document.createElement("form");
    //将form对象添加到body中
    document.body.appendChild(form);
    //设置form的属性,等价于<form action="XXX.action" method="post"></form>

    form.action = 'QuestionAction!pAsk';
    form.method = 'post';
    //创建隐藏input
    var newInput = document.createElement("input");
    newInput.setAttribute("type","hidden");
    newInput.setAttribute("name","title");
    newInput.setAttribute("value",title);
    //将隐藏input添加到form中
    form.appendChild(newInput);
    //提交form对象
    form.submit();
```

```

```

```

```

```

```

function post\_to\_url(path, params, method) {  
    method = method || "post"; // 把POST方法作为此预设

    var form = document.createElement("form"); // 在背后創建form元素  
    form.setAttribute("method", method); // 把form的method设成指定的方式, 上面预设成post的那个  
    form.setAttribute("action", path); // 接收post变数的网址

    for(var key in params) { // parms就是你所附上的变数阵列  
        var hiddenField = document.createElement("input"); //每一列都新建一个hidden的input  
        hiddenField.setAttribute("type", "hidden");  
        hiddenField.setAttribute("name", key); // , 以key作变数名, 其中的值为变数值  
        hiddenField.setAttribute("value", params\[key]);

        form.appendChild(hiddenField); // 把成了hidden input的变数加到才創建的form元素里  
    }

    document.body.appendChild(form); // 把form加到(不是显示)现在的页面上  
    form.submit(); // 把request送出去~  
}