<input type="button"> XMLHttpRequest 的不同行为与<按钮> [英] Different Behavior of XMLHttpRequest for <input type="button"> vs. <button>
问题描述
考虑以下代码:
index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form>
<button id="getInfoButton1"></button>
<input type="button" id="getInfoButton2"></input>
</form>
</body>
</html>
随附的 JavaScript 文件:
With the accompanying JavaScript file:
script.js
window.onload = initAll;
var req;
function initAll()
{
document.getElementById("getInfoButton1").onclick = getInfo;
document.getElementById("getInfoButton2").onclick = getInfo;
}
function getInfo()
{
req = new XMLHttpRequest();
var URL = "index.html";
req.open("GET", URL, true);
req.onreadystatechange = whatsTheStatus;
req.send(null);
}
function whatsTheStatus()
{
if (req.readyState != 4) { return; }
alert(req.status);
}
(我已经削减了很多代码,但这个例子仍然突出了错误)
(I've pared down my code a lot, but this example still highlights the error)
问题是这样的:当您加载它并单击两个按钮时,第一个将显示 0 的状态,而第二个将显示 200 的状态.
The question is this: When you load this, and click both buttons, the first one will display a status of 0, while the second one displays a status of 200.
当然,我希望两者都显示 200,但我不知道为什么 表现不同.这不是什么大不了的事,但我希望在整个网站中保持对
的相同使用.
Of course, I'm expecting both to display 200, and I have no idea why the <button>
is behaving differently. It's not a terribly big deal, but I would like to maintain the same use of <button>
throughout my site.
我浏览了网络并询问了我公司的其他一些开发人员,但我们似乎无法找到答案.有什么想法吗?
I've looked around the web and asked some other developers at my company, and we can't seem to find the answer. Any ideas?
如果有帮助,我正在 Firefox 3.6.8 上进行测试.另外,我通过 WAMPserver 2.0 从本地主机运行它.
If it helps, I'm testing on Firefox 3.6.8. Also, I'm running it from localhost via WAMPserver 2.0.
推荐答案
你需要 来重现
.
如果您省略 上的类型,则默认为
submit
(IE<8 除外,因为存在错误;因此,您应该始终使用 上的
type
属性).提交按钮会导致表单提交,导致导航并取消 XMLHttpRequest.
If you omit the type on <button>
it defaults to submit
(except on IE<8 due to a bug; for this reason you should always use a type
attribute on <button>
). A submit button would cause the form to submit, causing a navigation and cancelling the XMLHttpRequest.
一般来说,您应该在表单上设置 onsubmit
而不是在特定按钮上设置 onclick
,以确保您在表单是通过其他方式提交时始终得到通知,例如按下 Enter 键.(因此,您将使用普通的 submit
按钮.)使用事件处理程序中的 return false
来防止表单提交继续进行.
In general you should be trapping onsubmit
on the form rather than onclick
on a particular button, to ensure you always get informed if the form is submitted by another means such as Enter being pressed. (Consequently you'd use a normal submit
button.) Use return false
from the event handler to prevent the form submission from going ahead.
这篇关于<input type="button"> XMLHttpRequest 的不同行为与<按钮>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!