dongzhong2018 2012-01-11 14:15
浏览 96
已采纳

我可以使用提交按钮激活AJAX功能吗?

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条回答 默认 最新

  • dsgsdg206050 2012-01-11 14:17
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 eclipse连接sap后代码跑出来空白
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案