我正在使用 JSP Ajax 发送表单数据到 Servlet,但是 Ajax 响应在几纳秒内消失。

huangapple go评论74阅读模式
英文:

I am sending form data using jsp ajax to servlet and But ajax response gets disappear within nano seconds

问题

以下是翻译好的内容:

我通过Jsp在Servlet上使用AJAX发送表单数据。
reg.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
	"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form>
		输入姓名:<input type="text" id="name" /> <br />

		<button onclick="callJqueryAjax()">保存</button>
	</form>
	<span id="result"></span>

	<script
		src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script type="text/javascript">
		function callJqueryAjax() {
			var name = $('#name').val();
			console.log(name);

			$.ajax({
				url : 'Save',
				method : 'POST',
				data : {
					name : name,
				},
				success : function(resultText) {
					$("#result").html(resultText);
				}
			});
		}
	</script>
</body>
</html>

SaveMe.java

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Save")
public class SaveMe extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Connection makeCon;
	private Statement stmt;

	public void init(ServletConfig config) throws ServletException {
		JdbcCon jdbcCon = new JdbcCon();
		makeCon = jdbcCon.makeCon();
		try {
			stmt = makeCon.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse res)
			throws ServletException, IOException {
		String name = request.getParameter("name");

		res.setContentType("text/html");

		PrintWriter out = res.getWriter();

		String sql = "insert into users (name) Values('" + name + "')";
		System.out.println(sql);

		try {
			int result = stmt.executeUpdate(sql);

			if (result > 0) {
				out.print("已插入");
			} else
				out.print("未插入");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

我在AJAX中接收输出,但问题是JSP会自动重新加载,同时会删除响应,还会从文本框中删除数据,导致响应自动消失。请为我提供解决方案,以及更好的编写AJAX调用的方法。

英文:

I am sending form data using Jsp through AJAX on Servlet.<br>
reg.jsp

&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot;
pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
&lt;title&gt;Insert title here&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;form&gt;
Enter name:&lt;input type=&quot;text&quot; id=&quot;name&quot; /&gt; &lt;br /&gt;
&lt;button onclick=&quot;callJqueryAjax()&quot;&gt;Save&lt;/button&gt;
&lt;/form&gt;
&lt;span id=&quot;result&quot;&gt;&lt;/span&gt;
&lt;script
src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
function callJqueryAjax() {
location.reload(false);
var name = $(&#39;#name&#39;).val();
console.log(name);
$.ajax({
url : &#39;Save&#39;,
method : &#39;POST&#39;,
data : {
name : name,
},
success : function(resultText) {
$(&quot;#result&quot;).html(resultText);
}
});
}
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

SaveMe.java

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(&quot;/Save&quot;)
public class SaveMe extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection makeCon;
private Statement stmt;
public void init(ServletConfig config) throws ServletException {
JdbcCon jdbcCon = new JdbcCon();
makeCon = jdbcCon.makeCon();
try {
stmt = makeCon.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
String name = request.getParameter(&quot;name&quot;);
res.setContentType(&quot;text/html&quot;);
PrintWriter out = res.getWriter();
String sql = &quot;insert into users (name) Values(&#39;&quot; + name + &quot;&#39;)&quot;;
System.out.println(sql);
try {
int result = stmt.executeUpdate(sql);
if (result &gt; 0) {
out.print(&quot;Inserted&quot;);
} else
out.print(&quot;Not Inserted&quot;);
} catch (SQLException e) {
}
}
}

I receive the output in ajax but the thing is JSP gets reload by itself and removes the response as well as removes the data from Textbox from which my response gets disappear by itself.

Please provide me the solution and also a better way for writing an ajax call

答案1

得分: 0

首先,我不理解你在提交 ajax 请求之前为什么在你的 JSP 页面中使用了 "location.reload(false);"。
你可以将其删除。
此外,当使用 ajax 请求时,一个良好的实践是指定 "dataType",在你的情况下是 "html"。
以下是一个示例:

$.ajax({
    type: 'POST',
    url: 'SaveMe',
    success: function(result) {
        $("#result").html(result);
    },
    dataType: "html"
});
英文:

First of all I didn't understand why you are using "location.reload(false);" in your JSP page before submitting the ajax request.
You could remove it.
In addition a good practice when using ajax request is to specify the "dataType", in your case "html".
Here is an example:

    $.ajax( {
type : &#39;POST&#39;,
url : &#39;SaveMe&#39;,
success : function(result) {
$(&quot;#result&quot;).html(result);
},
dataType : &quot;html&quot;
});

huangapple
  • 本文由 发表于 2020年10月16日 15:43:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64384927.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定