使用onsubmit事件获取查询字符串

Get query string using onsubmit event

本文关键字:查询 字符串 获取 事件 onsubmit 使用      更新时间:2023-09-26

我想将表单提交转换为ajax请求。这是我的代码:

<html>
<head>
<meta charset="iso8859-9">
<script>
  document.addEventListener("DOMContentLoaded", function(event) {
    document.getElementById("query_form").onsubmit = function(event) {
        console.log(event);
        return false;
    }
  });
</script>
</head>
<body>
<form action="query.php" id="query_form" method="get">
<input name="first">
<input name="second">
<button type="submit">
</form>
<table id="results"></table>
</body>
</html>

我可以在onsubmit事件中读取计算的查询字符串以将其与ajax一起使用吗?或者我需要使用javascript自己创建它吗。如果可能的话,我不想使用外部库。

我可以在onsubmit事件中读取计算的查询字符串以将其与ajax 一起使用吗

没有。

我需要使用javascript 自己创建它吗

是的。

一般的解决方案包括循环遍历event.target.element、集合名称/值对,同时筛选出字段集、禁用的元素、未选中的复选框/单选按钮,正确处理多个选择,然后在加入&之前通过encodeURIComponent(name) + "=" + encodeURIComponent(value)传递所有结果。