当前位置:Gxlcms > AJAX > ajax的json传值方式在jsp页面中的应用

ajax的json传值方式在jsp页面中的应用

时间:2021-07-01 10:21:17 帮助过:34人阅读

jsp页面
代码如下:

$(document).ready(function() {
setInterval(function myTimer()
{
//alert('a');
getViews();
},1000);
});
//播放
function getViews(){
$.ajax({
'url':"${pageContext.request.contextPath}/video/getVideos.action?r="+Math.random()+"&open=1",
'data': '',
'dataType': 'json',
'type': 'get',
'error': function(data){
alert("error");
return false;
},
'success': function(data) {
if(null != data && '' != data){
//alert(data.updateFlag);
if(data.updateFlag==0){//如果data.updateFlag=0 不刷新
//alert("data.updateFlag=0");
}
else{
if(data.videoIds != null && data.videoIds != ""){
var listIds=data.videoIds;
var i=0;
for(;i<listIds.length;++i){
//alert("show:"+i+"id=:"+listIds[i]);
showView(listIds[i],i);//播放
}
for(var j=listIds.length;j<9;++j){
//alert("Stop:"+j);
StopPlayVideo(j);
}
}
}
}
}
});
}

此处由于此代码实现的功能是通过ajax定时访问后台Hashtable,所以为了是系统区别url不同、ajax返回值不同,特意在url后加上r=+Math.random()
java后台处理方法
代码如下:

/**
* 双服务器九宫格显示
*
* @return
*/
@Action(value = "getVideos" ,results={
@Result(name = SUCCESS,location="videos2.jsp")
})
public String getVideos() {
if (open == 301) {
return SUCCESS;
} else {
try {
VideoHashTable videoHashTable = VideoHashTable.getInstance();
Hashtable<Long, Long> hashTable = videoHashTable.getRht();
Map map = new HashMap<String, List<Long>>();
if (videoHashTable.isUpdateFlag() == true) {
Enumeration en = hashTable.keys();
videoIds = new ArrayList<Long>();
while (en.hasMoreElements()) {
Long key = (Long) en.nextElement();
// vth.get(key);
videoIds.add(key);
}
map.put("videoIds", videoIds);
map.put("updateFlag", 1L);
videoHashTable.setUpdateFlag(false);
System.out.println("getVideos:" + videoIds);
SendMessage.sendObject(map);
} else {
map.put("updateFlag", 0L);
SendMessage.sendObject(map);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

关键要把传到jsp的页面存到map中,在通过json传值。
SendMessage.sendObject(map)方法所在类及方法
代码如下:

package com.supcon.honcomb.utils;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpResponse;
import org.apache.struts2.ServletActionContext;
public class SendMessage {
public static void sendMessage(String responseText){
try {
PrintWriter out = ServletActionContext.getResponse().getWriter();
out.print(responseText);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void sendObject(Object obj) throws Exception {
PrintWriter pw;
String rtn = "";
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
rtn = JsonUtil.JsonFromObject(obj);
pw = response.getWriter();
pw.write(rtn);
pw.flush();
pw.close();
}
}

人气教程排行