【发布时间】:2018-11-24 16:27:24
【问题描述】:
我对 HTML 和 AJAX /JQuery 完全陌生。我想在同一页面上显示form 中给出的输入结果。
下面是代码sn-p。
<div id = "test">
<form id="ajax-contact" method="post" action="/response/">
<div class="field">
<label for="name">your text here</label>
<input type="text" id="name" name="name" required>
</div>
<div class="field">
<button>Submit</button>
</div>
</form>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post(
{
type:'POST',
url:$(form).attr('action')
data: $(form).serialize()
},
function(response,status){
alert("Data: " + resp_final + "\nStatus: " + status);
});
});
});
在上面的 sn-p 中,resp_final 是从服务器检索的值,其中 response 是执行必要计算/处理的服务器路由。
这很好用。但是,结果显示在单独的页面上。我想在同一页面上显示结果。
有人可以帮忙吗?
【问题讨论】:
-
由于您的按钮是默认类型 (
submit),它将发布您的表单,结果将作为新的 HTML 内容收集。您应该尝试将该按钮更改为<button type="button">Submit</button>。 -
html 按钮的“type”属性的可能值: submit:按钮将表单数据提交给服务器。如果未指定属性,或者属性动态更改为空值或无效值,则这是默认值。重置:该按钮将所有控件重置为其初始值。按钮:按钮没有默认行为。它可以具有与元素事件相关联的客户端脚本,这些事件在事件发生时被触发。 (取自developer.mozilla.org/en-US/docs/Web/HTML/Element/button)