ajax点击链接获取服务器端数据

显示商品信息版本1:

案例如下,点击链接显示商品信息,就显示如下表格信息.


1.首先创建一个Product的类.

package cn.com.domain;

public class Product {
	private int id;
	private String name;
	private double price;
	private String type;

	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public Product() {
		super();
	}
	public Product(int id, String name, double price) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
}

ajax4jsp的代码如下.

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>ajax开发---显示商品信息</title>

<script type="text/javascript" src="${pageContext.request.contextPath}/my.js"></script>
<script type="text/javascript">
	window.onload = function() {
		//得到id=t的文本框
		var p = document.getElementById("p");
		p.onclick = function() {

			//第一步:得到XMLHttpRequest对象.
			var xmlhttp = getXmlHttpRequest();
			//2.设置回调函数
			xmlhttp.onreadystatechange = function() {
				//5.处理响应数据  当信息全部返回,并且是成功
				if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
					var msg = xmlhttp.responseText;
					document.getElementById("d").innerHTML = msg;
				}
			};
			//post请求方式,参数设置
			xmlhttp.open("GET", "${pageContext.request.contextPath}/ajax4");
			xmlhttp.send(null);
		};
	};
</script>
</head>

<body>
	<a href="javascript:void(0)" id="p">显示商品信息</a>
	<div id="d"></div>
</body>
</html>

服务器端的Ajax4Servlet.java文件的代码.

package cn.itcast.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.com.domain.Product;

public class Ajax4Servlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		List<Product> ps = new ArrayList<Product>();
		ps.add(new Product(1, "洗衣机", 1800));
		ps.add(new Product(2, "电视机", 3800));
		ps.add(new Product(3, "空调", 5800));

		PrintWriter out = response.getWriter();
		StringBuilder builder = new StringBuilder();
		builder.append("<table border='1'><tr><td>商品编号</td><td>商品名称</td><td>商品价格</td></tr>");
		for(Product p : ps){
			builder.append("<tr><td>"+p.getId()+"</td><td>"+p.getName()+"</td><td>"+"</td><td>"+p.getPrice()+"</td><td>");
		}
		
		builder.append("</table>");
		
		out.print(builder.toString());
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

图片展示效果.



显示商品信息版本2:

        创建一个product.jsp页面,在页面上去组装table,直接将数据返回了.

修改了Ajax4Servlet.java文件的代码,如下所示.

package cn.itcast.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.com.domain.Product;
public class Ajax4Servlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		List<Product> ps = new ArrayList<Product>();
		ps.add(new Product(1, "洗衣机", 1800));
		ps.add(new Product(2, "电视机", 3800));
		ps.add(new Product(3, "空调", 5800));

		request.setAttribute("ps", ps);
		
		request.getRequestDispatcher("/product.jsp").forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

并且再新建一个Product.jsp文件,代码如下.

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<table border='1'>
	<tr>
		<td>商品编号</td>
		<td>商品名称</td>
		<td>商品价格</td>
	</tr>
	<c:forEach items="${ps}" var="p">
		<tr>
			<td>${p.id }</td>
			<td>${p.name }</td>
			<td>${p.price }</td>
		</tr>
	</c:forEach>
</table>

图片显示如下.



显示商品信息版本3:

    在服务器端得到数据,只将要显示的内容返回,而不返回html代码,也就是服务器只是发送数据,而让功能越来越强大的浏览器来处理收到的数据,将其显示出来.

    而html代码的拼接,在浏览器端完成.

版本三的ajax5.jsp的代码如下.

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>ajax开发---显示商品信息(json)</title>

<script type="text/javascript" src="${pageContext.request.contextPath}/my.js"></script>

<script type="text/javascript">
	window.onload = function() {
		//得到id=t的文本框
		var p = document.getElementById("p");

		p.onclick = function() {

			//第一步:得到XMLHttpRequest对象.
			var xmlhttp = getXmlHttpRequest();
			//2.设置回调函数
			xmlhttp.onreadystatechange = function() {

				//5.处理响应数据  当信息全部返回,并且是成功
				if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

					var json = eval(xmlhttp.responseText);    
					
					var msg="<table border='1'><tr><td>商品编号</td><td>商品名称</td><td>商品价格</td></tr>";
					
					for(var i=0;i<json.length;i++){
						msg+="<tr><td>"+json[i].id+"</td><td>"+json[i].name+"</td><td>"+json[i].price+"</td></tr>";
					}
					msg+="</table>";
					
					document.getElementById("d").innerHTML=msg;
				}
			};

			//post请求方式,参数设置
			xmlhttp.open("GET", "${pageContext.request.contextPath}/ajax5");

			xmlhttp.send(null);
		};
	};
</script>

</head>
<body>
	<a href="javascript:void(0)" id="p">显示商品信息</a>

	<div id="d"></div>
</body>
</html>

eval是JavaScript的一个方法,可以将获得的字符串变成JavaScript的代码,

var a = "alert('hello')";        里面的 alert('hello');  是js代码但是是字符串,

eval(a);      通过eval就可以将其转换为js代码.

json代码:    [{'id':'1','name':'洗衣机','price':'1800'},{'id':'2','name':'电视机','price':'3800'}]

下面是Axaj5Servlet的代码.

package cn.itcast.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import cn.com.domain.Product;
import cn.itcast.jsonlib.JsonLibTest;

public class Ajax5Servlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		// 返回的是json数据
		PrintWriter out = response.getWriter();

		out.print("[{'id':'1','name':'洗衣机','price':'1800'},{'id':'2','name':'电视机','price':'3800'}]");    //这返回的就是json数据
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

将会显示和之前的页面是一样的.


若在ajax5里面通过,

var json = xmlhttp.responseText;

alert(json);

将会显示字符串,通过eval转换为js代码,即可以显示数据.






猜你喜欢

转载自blog.csdn.net/superman___007/article/details/80745236