can I use the submit button to activate an AJAX fu

2019-08-10 07:03发布

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>

4条回答
爷、活的狠高调
2楼-- · 2019-08-10 07:34

Of course you can. But it's more useful to call your Javascript function in the input like this :

 <input type="submit" value="Submit" onclick="ajax();" />

And remove the action part in the form.

查看更多
爷的心禁止访问
3楼-- · 2019-08-10 07:35

I jQuery you can use event.preventDefault(); otherwise just use return false;

http://jsfiddle.net/mKQmR/

http://jsfiddle.net/mKQmR/1/

查看更多
疯言疯语
4楼-- · 2019-08-10 07:41

Pointy is correct... just add a click handler to the submit button, however make sure the last line of the click handler returns "false" to prevent the form from actually being posted to the form's action.

<html>
<head>
<script type="text/javascript">
function ajax(){
  //...
return false;
}
</script>
</head>

<body>
<form action="thispage.htm">
  <!-- ... -->
  <input type="submit" value="Submit" onclick="ajax();" />
</form>
</body>
</html>
查看更多
冷血范
5楼-- · 2019-08-10 07:49

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.

查看更多
登录 后发表回答