这个问题已被多次询问过。但我得到了一个共同的答案,即通过response.getwriter().write("....")
内部servlet发送响应。但这不是通过ajax发送响应的实际方式。我想通过响应更新<div>
而不是整页。但我没有找到解决方案。我的代码如下: -
的index.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>
</head>
<body>
<script src="jquery.js" ></script>
<form name="myForm" method="post" id="search" action="al">
<input type="text" name="fname"/>
<input type="submit" value="Search" id="button1"/>
</form>
<div id="some">
</div>
<script>
$("#myForm").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(response)
{
$("#some").text(response);
//console.log(response);
//data: return data from server
},
error: function(response)
{
//if fails
}
});e.preventDefault();});
});
</script>
</body>
</html>
AddressLocator.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name=request.getParameter("fname");
//response.getWriter().println("abc.html");
//response.sendRedirect("getData");
URL oracle = new URL("https://maps.googleapis.com/maps/api/geocode/json?address="+name);
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
response.getWriter().write(inputLine);
in.close();
}
这里,al映射到AddressLocator类。 请提前帮助... thanx ..