Lecture 7: Use ajax technology to realize pop-up product details prompt function (xml data)

Use ajax technology to realize the pop-up product details prompt function. In this case, the original ecological xmlhttprequest object is used, and the GET method is used for asynchronous communication. The background uses map to save the search data. After the corresponding data is queried, the data in xml format is returned, and the front end uses the responseXML attribute to return xml Format data, parse the content of the xml file, and combine JavaScript to locate and display product details.

ajax package object (ajax.js)

var xmlhttp=null;
//创建XMLHttpRequest对象
function createHttpRequest(){
    if(window.XMLHttpRequest){ //Mozilla 浏览器
        xmlhttp = new XMLHttpRequest();
    }else if(window.ActiveXObject){
        try{
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); //新版IE
        }catch(e){
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }catch(e){
                xmlhttp = null;
            }
        }
    }
    if(!xmlhttp){ //创建XMLHttpRequest失败
        alert("不能创建XMLHttpRequest对象实例");
    }
}
//发送函数
function sendRequest(method,url,param,callbackHandler){
    //创建对象
    createHttpRequest();
    //绑定事件,后台返回的数据,通过callback方法处理
    xmlhttp.onreadystatechange = callbackHandler;

    if(method=="get" || method=="GET"){
        //初始化发送信息
        xmlhttp.open(method,url + "?" + param,true);
        xmlhttp.send(null);
    }

    if(method=="post" || method=="POST"){
        //初始化发送信息
        xmlhttp.open(method,url,true);
        xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xmlhttp.send(param);
    }
}

Front-end page (tip.html)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb18030" />
<title>Ajax应用举例</title>
<script type="text/javascript" src="../js/ajax.js"></script>
<script type="text/javascript">
	var eposx ;
	var eposy ;
	function showRequest(pid){
	    //获取鼠标当前位置
		eposx = event.offsetX;
		eposy = event.offsetY;
		var url="/ajaxProj/T2/tip.jsp";
		var params = 'pid='+ pid + '&time=' + (new Date()).toString() ;
		sendRequest('GET',url,params,showDetail);
	}
	
	//动态加载数据部门列表
	function showDetail(){
		if (xmlhttp.readyState == 4) { 
			if (xmlhttp.status == 200) {
				var membersData = xmlhttp.responseXML.getElementsByTagName("member");
				var membersList = document.getElementById("detail");
				//循环将数据插入列表框中
				var li = '<table>';
				for(var i=0;i<membersData.length;i++){
					var price=membersData[i].childNodes[0].firstChild.nodeValue;
					var num=membersData[i].childNodes[1].firstChild.nodeValue;
					var chandi=membersData[i].childNodes[2].firstChild.nodeValue;
					li += '<tr><td>价格:' + price + '</td></tr>';
					li += '<tr><td>数量:' + num + '</td></tr>';
					li += '<tr><td>产地:' + chandi + '</td></tr>';
				}
				li += '</table>';
				membersList.innerHTML = li;
				//移动到鼠标的位置
				setDivPosition();
				//显示div
				membersList.style.visibility='visible';
			} else { //页面不正常 
				alert("您请求的页面有异常"); 
			}
		}
	}
	//异常detail标签
	function hidendiv(){
		var membersList = document.getElementById("detail");
		membersList.innerHTML = '';
		membersList.style.visibility='hidden';
	}
	
	function setDivPosition(){
		var goodslist = document.getElementById('goodslist');
		eposx = goodslist.offsetLeft + goodslist.offsetWidth -2;
		eposy += goodslist.offsetTop + 2;
		var listdiv = document.getElementById('detail');
		listdiv.style.left=eposx+'px';
		listdiv.style.border='blue 1px solid';
		listdiv.style.top=eposy + 'px';
		listdiv.style.width='100px';
		listdiv.style.zIndex='999';
	}
</script>
</head>
<body>
<h1>数据提示</h1>
<hr />
商品列表:
<p id="goodslist" style="float:left;" onmouseout="hidendiv();">
<a href="javascript:void(0);" onmouseover="showRequest('p1');" >商品A</a><br/>
<a href="javascript:void(0);" onmouseover="showRequest('p2');" >商品B</a><br/>
<a href="javascript:void(0);" onmouseover="showRequest('p3');">商品C</a><br/>
</p>
<div id="detail" style="background-color:green;position:absolute;visibility:hidden">
</div>
</body>
</html>

Background function (tip.jsp)

<%@ page contentType="text/xml; charset=gb18030"%><%@ page import="java.util.*"  %><%
	Map map = new HashMap();
	String p1 = "<member><price>10.5</price><num>50</num><chandi>北京</chandi></member>";
	String p2 = "<member><price>30</price><num>20</num><chandi>上海</chandi></member>";
	String p3 = "<member><price>50</price><num>10</num><chandi>武汉</chandi></member>";
	map.put("p1",p1);
	map.put("p2",p2);
	map.put("p3",p3);


	String pid= request.getParameter("pid");
	System.out.println(pid);
	StringBuffer sb = new StringBuffer();
	sb.append("<members>");	
	sb.append(map.get(pid).toString());
	sb.append("</members>");
	out.write("<?xml version='1.0' encoding='gb2312' ?>");
	out.write(sb.toString());
%>

Special Note:

1. There cannot be any comment lines at the top of the page, and there must be no spaces;

2. There can be no blank lines or spaces between the page command and the jsp code.

 running result

          

I have been engaged in software project development for more than 20 years. Since 2005, I have been engaged in teaching Java engineer series courses. I have recorded more than 50 high-quality video courses, including java basics, jspweb development, SSH, SSM, SpringBoot, SpringCloud, artificial intelligence, online payment, etc. Commercial projects, each course includes project practice, class PPT, and complete source code download, interested friends can take a look at my online classroom

Lecturer classroom link: https://edu.csdn.net/lecturer/893

Guess you like

Origin blog.csdn.net/software7503/article/details/131349266