动态加载网页的途径

1.网页向服务器发出请求得到数据后利用JS完成动态加载

例:
ps:整段代码可能在大家的机器上运行起来会报错

(原因是代码中一些class的设置和路径)

但是,代码我是亲自测试过 ok 的 大家可以借鉴,我也加了一些注释

网页端

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery-2.1.4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
	function get_info(){
		$.ajax({ //利用ajax对象发送请求
        type: "GET",
        url:"http://localhost:8080/first/Doit",
        dataType: "json",
        jsonp: "callback",
        success: function(json){ //接收到数据后运行这个函数,json对象是返回的数据
        	var i=0;
        	while(json[i]){ //这里我服务器返回的是jsonarray的数据所以用下标的方式访问,只要json[i]不为空就循环下去
        		var item ="车价:"+json[i].price+"";
                $("#biao").append(item);//内容添加到当前页面上,#biao表示id是biao的标签
                i++;
        	}
            
        },
        error: function(){
            alert("fail");
        }
    });
	}
</script>
</head>
<body>
<center>
	<h2>二手车市场</h2>
</center>

<table class="table table-bordered" id="biao"></table>
<table ></table>
<script>get_info()</script>
</body>
</html>

服务器端:(Javaee)

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
	    response.setContentType("application/json; charset=utf-8");//返回json
		int i=1;
		JSONObject json=new JSONObject(); //这里是服务器封装jsonarray数据的方式
		JSONArray J=new JSONArray();
		json.put("name","劳斯莱斯" );//把单个jsonobject装进jsonarray就可以了
		json.put("price","100" );
		J.add(json);
		json.clear();
		json.put("name","奔驰" );
		json.put("price","80" );
		J.add(json);
		System.out.println(J);
		PrintWriter out = response.getWriter();  
        out.append(J.toString()); //给网页发送json数据
	}

2.网页向服务器发出请求后,服务器直接返回带有数据的网页

ps:下面这段代码同上,只供大家借鉴

服务器端
void send_market(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException{
		Connection connection=cpds.getConnection();
		request.setCharacterEncoding("utf-8");
	    response.setContentType("text/html; charset=utf-8");//返回HTML网页
		String sql = "SELECT car_id,name,addr,price,distance,out_put,degree FROM first.market where car_id=?";
		String id=request.getParameter("id");
		Object[] objs = {id};
		Market M=doit.fetchMarket(connection, sql, objs);//从数据库取数据并封装到Market对象里
		PrintWriter out = new PrintWriter(response.getWriter());  
		//这里就是服务器用out对象返回一个HTML网页
		out.write("Insert title here

汽车详情

)); out.write(">


车名:"); out.write(M.getName()); out.write("
车价:"); out.write(String.valueOf(M.getPrice()) ); out.write("
城市:"); out.write(M.getAddr()); out.write("
里程:"); out.write(String.valueOf(M.getDistance())); out.write("
档数:"); out.write(String.valueOf(M.getDegree())); out.write("
排量:"); out.write(String.valueOf(M.getOut_put())); out.write("
"
); }

你可能感兴趣的:(Java,Java)