【发布时间】:2010-07-08 19:11:01
【问题描述】:
我正在尝试为我的网站编写一些 JavaScript,它将选择页面上的所有表单,在提交时添加事件侦听器,然后将提交的值路由到主操作页面和其他备用页面.
这是我目前所拥有的:
发送.php:
<script type="text/javascript">
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
document.body.appendChild(form); // Not entirely sure if this is necessary
form.submit();
}
function addEvent(elm, evType, fn, useCapture) {
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture);
return true;
}
else if (elm.attachEvent) {
var r = elm.attachEvent('on' + evType, fn);
return r;
}
else {
elm['on' + evType] = fn;
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
}
else {
window.onload = function() {
oldonload();
func();
}
}
}
function addSubmits() {
var fs=document.forms;
for(var i=0;i<fs.length;i++){
//addEvent(fs[i],"submit",post_to_url('http://www.gwtwg.com/recieve.php', {'email' : 'test.com'}), false)
}
}
addLoadEvent(addSubmits);
</script>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<input type="text" name="email" />
<input type="submit" value="Submit!" />
</form>
现在脚本只是冻结了,但如果我替换:“post_to_url('http://www.gwtwg.com/recieve.php', {'email' : 'test.com'})” 和: “警报(“foobar”)”
我在加载页面和提交表单时收到警报。 (它应该只在提交按钮时发生)。
有什么想法吗?
【问题讨论】:
标签: javascript forms post events