fsc*_*ore 6 java ajax jquery jsp servlets
我试图通过ajax将jsp等基本值传递给servlet.我尝试了一切,但只传递了null.甚至console.log(val)不会向浏览器控制台打印任何内容.
我的理解是:网页有表单值,提交调用js文件.js有一个调用servlet并传递表单数据的ajax.servlet从ajax中获取数据request.getParameter(val)
这是我的代码:
main.jsp中
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript">
<script src="js/main.js" type="text/javascript"></script>
</head>
<body>
<form method="post" action="Main" id="firstform">
<h1>Enter name:</h1>
<input type="text" name="id" id="id" />
<input type="submit" name="submit"/>
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
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;
});
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
**问题:
1)从jsp传递给servlet的值
2)console.log不会在浏览器控制台上打印任何内容
1)工作,但2)仍然没有.**
| 归档时间: |
|
| 查看次数: |
25924 次 |
| 最近记录: |