gpt4 book ai didi

java - 使用 JQuery Ajax 将表单提交到 servlet

转载 作者:行者123 更新时间:2023-12-01 02:20:49 26 4
gpt4 key购买 nike

当我们使用Jquery Ajax点击span标签时,如何将Form提交给servlet,并从servlet获取输出?下面是计算器示例代码。如果我使用 input type="submit"而不是 span,我会在 index.html 中得到正确的结果,但如果我使用 span 而不是 input type 进行提交,我将被定向到 servlet 页面。

index.html

<form name="form1" method="POST" action="Ajaxexample" id="form1">
<table>
<tr>
<td>Number 1</td><td><input type="text" name="n1"/></td>
</tr>
<tr>
<td>Number 2</td><td><input type="text" name="n2"/></td>
</tr>
<tr>
<td></td><td><span onclick="form1.submit()">Calculate</span></td>
</tr>
<tr>
<td>Result</td><td><input type="text" value="" id="result"/></td>
</tr>
</table>
</form>
<script src="script/jquery-1.10.2.min.js"></script>
<script type="text/javascript">

var form = $('#form1');
form.submit(function () {

$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: value,
success: function (data) {
var result=data;
$('#result').attr("value",result);
}
});
return false;
});
</script>

Ajaxexample.java

     protected void doGet(HttpServletRequest request, HttpServletResponse response)throws 
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

int n1 = Integer.parseInt(request.getParameter("n1"));
int n2 = Integer.parseInt(request.getParameter("n2"));

out.println(n1 + n2 + "");

}
}

web.xml

      <display-name>Ajax</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Ajaxexample</servlet-name>
<servlet-class>Ajaxexample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Ajaxexample</servlet-name>
<url-pattern>/Ajaxexample</url-pattern>
</servlet-mapping>

最佳答案

<span onclick="formSubmit();">Calculate</span>

function formSubmit(){

$.ajax({
url:'localhost:8080/Ajax/Ajaxexample',
data: $("#form1").serialize(),
success: function (data) {
$('#result').html(data);
}
});
}

关于java - 使用 JQuery Ajax 将表单提交到 servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20581259/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com