我目前刚并将数据直接传递到PHP文件的HTML表单。我想更新code,使提交按钮将数据发送到一个JavaScript函数,这样我可以创造一个AJAX功能。是否有可能为提交按钮激活JavaScript函数,而不是张贴到一个PHP文件?我想出的唯一的事情是低于,这很显然是行不通的:
< HTML>
< HEAD>
<脚本类型=文/ JavaScript的>
功能AJAX(){
// ...
}
< / SCRIPT>
< /头>
<身体GT;
<形式的行动=阿贾克斯();>
< - !... - >
<输入类型=提交值=提交/>
< /形式GT;
< /身体GT;
< / HTML>
解决方案
您可以给提交输入点击处理程序,明确prevents从正在开展的默认行为。
<输入类型=提交值=提交的onclick ='AJAX(事件),'>
然后在功能:
函数AJAX(事件){
如果(在事件'preventDefault')事件preventDefault()。
event.returnValue = FALSE; IE9之前//对于IE浏览器
// ...
}
修改的@Esailija指出正确的另一种选择是处理上的&LT提交事件;形式>
元素来代替。该功能看起来pretty的大同小异,其实完全一样,但你连线它是这样的:
<形式ID ='yourForm'的onsubmit =AJAX(事件),'>
这也将捕获的东西,如Enter键操作等。
I have an HTML form that currently just posts the data directly to a PHP file. I want to update the code so that the submit button sends the data to a JavaScript function so that I can create an AJAX function. Is it possible for the submit button to activate a JavaScript function rather than posting to a php file? The only thing I have come up with is below, which quite obviously does not work:
<html>
<head>
<script type="text/javascript">
function ajax(){
//...
}
</script>
</head>
<body>
<form action="ajax();">
<!-- ... -->
<input type="submit" value="Submit" />
</form>
</body>
</html>
解决方案
You can give the "submit" input a "click" handler that explicitly prevents the default behavior from being carried out.
<input type='submit' value='Submit' onclick='ajax(event)'>
Then in the function:
function ajax(event) {
if ('preventDefault' in event) event.preventDefault();
event.returnValue = false; // for IE before IE9
// ...
}
edit @Esailija points out correctly that another option is to handle the "submit" event on the <form>
element instead. The function would look pretty much the same, in fact exactly the same, but you'd wire it up like this:
<form id='yourForm' onsubmit='ajax(event)'>
That will also trap things like the "Enter" key action, etc.
上一篇:的fancybox链接并不Ajax内容里面工作并不、里面、链接、内容
下一篇:JSP:调用RequestDispatcher.forward()不转发时,通过Ajax POST所谓的servletforward、RequestDispatcher、JSP、servlet