我正在尝试使用Ajax,Servlet和HTML从我的数据库中删除用户。当我提交数据时发生非法调用。我认为连接或SQL语句没有任何问题
delete.html
<input type="text" id="delete">
<input type="submit" onclick="deleteUSer()" value="Delete">
delete.js
function deleteUSer(){
var username = document.getElementById("delete");
var params = {
username: username
}
$.post("Delete", params, function(data){}
)
}
Delete.java servlet
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = null;
DBUtils dbutils = null;
Connection conn = null;
try{
String username = request.getParameter("username");
dbutils = new DerbyUtils();
conn = dbutils.getConnection();
DeleteDAO dao = new DeleteDAO(conn);
dao.deleteUser(username);
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/index.html");
dispatcher.forward(request, response);
}
DeleteDAO.java
public void deleteUser(String username) throws SQLException{
try{
String sql = "delete from users where username='"+username+"'";
PreparedStatement ps = this.conn.prepareStatement(sql);
ps.executeQuery();
答案 0 :(得分:0)
您发送的是html doc elemect而非用户名...
试试这个 -
<input type="text" id="delete" value="vivek">
<input type="submit" onclick="deleteUSer()" value="Delete">
function deleteUSer(){
var username = document.getElementById("delete");
var params = {
username: username.value
}
$.post("Delete", params, function(data){}
)
}
答案 1 :(得分:0)
如果你正试图制定&#34;删除&#34;您可以使用HTTP请求的命令,您想要使用$.ajax
,而不是$.post
。
引用文档(https://api.jquery.com/jQuery.post/):
这是一个简写的Ajax函数,相当于:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
如果你正试图制定&#34;删除&#34;,你想做的事情如下:
var dataObj = {
'username': document.getElementById("delete").value;
}
$.ajax({
type:"DELETE",
data: dataObj,
url: 'url/to/your/servlet'
});
你可能还想在其中包含一个数据类型,但是对于这个例子,jquery可以解决它。