我试图通过ajax将jsp等基本值传递给servlet.我尝试了一切,但只传递了null.甚至console.log(val)也不会向浏览器控制台打印任何内容.
我的理解是:网页有表单值,提交调用js文件. js有一个调用servlet并传递表单数据的ajax. servlet通过request.getParameter(val)从ajax中获取数据
这是我的代码:
main.jsp中
pageEncoding="ISO-8859-1"%>
Insert title hereEnter name:
main.js
var form = $('#firstform');
console.log("gi");
form.submit(function()
{
$.ajax({
url: 'Main',
data: form.serialize(),
type: 'post',
success: function(data){
console.log(data);
}
});
//return false;
});
Main.java
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Main
*/
@WebServlet("/Main")
public class Main extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Main() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
int ids;
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String val = request.getParameter("id");
System.out.print(val);
if(val != null){
ids = Integer.parseInt(val);
out.print(ids); //
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
**问题:
1)从jsp传递给servlet的值
2)console.log不会在浏览器控制台上打印任何内容
1)工作,但2)仍然没有.**
解决方法:
在main.js类型中是type:’post’,你在get方法中编写了代码
输入:’get’
标签:jquery,java,ajax,jsp,servlets
来源: https://codeday.me/bug/20190517/1119847.html