我想将表单提交转换为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 自己创建它。如果可能的话,我不想使用外部库。
最佳答案
Can I just read calculated query string in onsubmit event to use it with ajax
没有。
do I need to create it myself using javascript
是的。
一般的解决方案将涉及循环遍历 event.target.elements、集合名称/值对,同时过滤掉字段集、禁用元素、未选中的复选框/单选按钮,正确处理多个选择,然后通过 encodeURIComponent( name) + "="+encodeURIComponent(value)
在加入 &
之前。
关于javascript - 使用 onsubmit 事件获取查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34413493/