首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript:使用JavaScript填写JavaScript表单并提交

JavaScript:使用JavaScript填写JavaScript表单并提交
EN

Stack Overflow用户
提问于 2014-10-17 13:53:20
回答 1查看 3.9K关注 0票数 0

我需要像这样填写HTML表单:

代码语言:javascript
复制
<form action="http://www.example.net/index.php" method="post">
<div class="poll">
<p class="poll-answer">
<label><input type='radio' name='option_id' value='12' />Abc</label>
</p>
<p class="poll-answer">
<label><input type='radio' name='option_id' value='34' />Def</label>
</p>
<input type="hidden" name="poll_id" value="56" />
<input type="submit" value="Submit!" />
</div>
</form>

我需要用JavaScript填写并发送。

我写了:

代码语言:javascript
复制
<script>
function post(path) {
    method = "post";
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    var hiddenField = document.createElement("input");
    hiddenField.setAttribute("type", "radio");
    hiddenField.setAttribute("name", "option_id");
    hiddenField.setAttribute("value", "12");

    hiddenField.setAttribute("type", "hidden");
    hiddenField.setAttribute("name", "poll_id");
    hiddenField.setAttribute("value", "56");

    form.submit();
}
post('http://www.example.net/index.php');
</script>

但作为回应,没有数据。我需要发送带有狭长的Abc = value='12'的表单。表单操作不在我的域中。我有a.com,form在b.com

代码语言:javascript
复制
# nc -l 192.168.1.11 -p 80
POST /index.php HTTP/1.1
Host: example.net
Connection: keep-alive
Content-Length: 0
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: null
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.101 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip,deflate
Accept-Language: cs-CZ,cs;q=0.8

我做了什么坏事?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-17 13:59:08

您忘记将隐藏字段附加到表单中,并将表单附加到文档中。

代码语言:javascript
复制
<script>
function post(path) {
    method = "post";
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    var hiddenField = document.createElement("input");
    hiddenField.setAttribute("type", "radio");
    hiddenField.setAttribute("name", "option_id");
    hiddenField.setAttribute("value", "12");

    form.appendChild(hiddenField);

    hiddenField = document.createElement("input");
    hiddenField.setAttribute("type", "hidden");
    hiddenField.setAttribute("name", "poll_id");
    hiddenField.setAttribute("value", "56");

    form.appendChild(hiddenField);
    document.body.appendChild(form);

    form.submit();
    }
post('http://www.example.net/index.php');
</script>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26426616

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档