我想获取HTML表单的一个字段,并使用它来修改操作的URL。我关注了this question,其中显示了GET请求是如何完成的,但我在修改POST请求的技术时遇到了问题。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>User location lookup</title>
</head>
<body>
<!-- method: https://stackoverflow.com/questions/11811782/form-value-creates-a-url -->
<script>
function process()
{
var url="http://localhost:43/" + document.getElementById("url").value;
location.href=url;
return false;
}
</script>
<form onSubmit="return process();" method="get">
Username: <input type="text" name="url" id="url"></input>
<input type="submit" value="go"></input>
</form>
<script>
function process2()
{
var url="http://localhost:43/" + document.getElementById("url").value;
location.href=url;
return false;
}
</script>
<form method="post" onSubmit="return process2();">
Username: <input type="text" name="url" id="url"> </input>
Location: <input type="text" name="location" id="location"> </input>
<input type="submit" value="go"></input>
</form>
</body>
</html>
GET请求正确发送:
GET /brian HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: en-GB
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko
Accept-Encoding: gzip, deflate
Host: localhost:43
DNT: 1
Connection: Keep-Alive
对于POST我得到了:
GET /brian HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: en-GB
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko
Accept-Encoding: gzip, deflate
Host: localhost:43
DNT: 1
Connection: Keep-Alive
即使该方法为POST
,仍然是GET。
我想要产生的是:
POST /brian HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: en-GB
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko
Accept-Encoding: gzip, deflate
Host: localhost:43
Content-Length: 11
DNT: 1
Connection: Keep-Alive
location=SO
有人可以用尽可能少的JavaScript代码指出我正确的方向吗?
答案 0 :(得分:4)
您的代码未提交表单。它实际上是通过GET直接调用URL,即:此方法仅适用于GET。
请尝试:
<form id="myformid" method="post">
Username: <input type="text" name="url" id="url2" onChange="updateAction()"> </input>
Location: <input type="text" name="location" id="location"> </input>
<input id="mysubmit" type="submit" value="go"></input>
</form>
<script>
function updateAction() {
var url = document.getElementById("url2").value;
document.getElementById("myformid").setAttribute("action", "http://localhost:43/" + url);
}
</script>