jQuery 完成ajax传jsonObject数据,并在后台处理

时间:2022-08-20 17:10:37

效果图:

jQuery 完成ajax传jsonObject数据,并在后台处理

1.js文件封装的几个js工具

<span style="font-family:KaiTi_GB2312;font-size:18px;">//兼容ie
if (typeof JSON == 'undefined') {
$("head").append($("<script type='text/javascript' src='http://www.huimg.cn/app/baikesurvey/js/json2.js'></script>"));
}
/**
* 工具对象,包括全部的公共方法。 */
var giftShopTool = {
dialogId : "giftDialog",
jsloadArray : [],
// 关闭允许弹窗
closeHDdialog : function() {
setTimeout(function() {
$.dialog.close(giftShopTool.dialogId);
}, 500);
},
HDdialog : function(title, content, width, height) {
$.dialog({
id : giftShopTool.dialogId,
title : title,
effects : 'fade',
height : height,
width : width,
content : content,
resetTime : -1,
styleContent : {
textAlign : 'left'
}
});
}
};
/**
* 取消对话框
*
* @return
*/
function cancel() {
giftShopTool.closeHDdialog();
} function selectAll() { var selectall = document.getElementById("checkAll");
var checkboxid = document.getElementsByName("outerNewsId");
if (selectall.checked == true) {
for ( var i = 0; i < checkboxid.length; i++) {
checkboxid[i].checked = true;
}
} else {
for ( var i = 0; i < checkboxid.length; i++) {
checkboxid[i].checked = false;
}
}
} /**
* 全选关联词条
*
* @returns
*/
function complexRelateDoc() {
var objArray = [];
var idList = document.getElementsByName("outerNewsId");
// 检查是否选择内容
for (i = 0; i < idList.length; i++) {
if (idList[i].checked) {
var checkId = idList[i].value;
var id = $("#id" + checkId).html();
var title = $("#title" + checkId).html();
var name = $("#name" + checkId).val();
var url = $("#url" + checkId).val();
var date = $("#date" + checkId).val();
var model = {
"id" : id,
"title" : title,
"name" : name,
"url" : url,
"date" : date
};
objArray.push(model);
}
}
return JSON.stringify(objArray);
} /**
* 初始化关联词
* @returns
*/
function initKeyWord(){
for (var i = 1; i < 6; i++) {
var keyword = $("#searchKeyword" + i).val();
if (keyword!=""||keyword!=undefined) {
if (keyword.indexOf(",")!=-1 || keyword.indexOf("。")!=-1) {
alert("输入的參数不合法:关键词中不能包括,和,");
}
$("#input" + (i-1)).val(keyword);
}
}
}
/**
* 单选关联词条
*
* @param id
* @param title
* @param name
* @param url
* @param time
* @returns
*/
function singleRelateDoc(id, title, name, url, date) {
var model = {
"id" : id,
"title" : title,
"name" : name,
"url" : url,
"date" : date
};
var objArray = [];
objArray.push(model);
return JSON.stringify(objArray); }
/**
* 关联词条编辑窗体
*
* @param models
*/
function showRelateDocPage(flag, id, title, name, url, date) { var tableTr = "";
for ( var i = 1; i < 10; i++) {
tableTr += "<tr><td></td><td><input type='text' name='input" + i + "' id='input" + i + "' value=''></td><td><input type='button' value='清空' onclick=\"clearInput('input" + i + "' )\"></td></tr>";
}
var html = "<table><tr><td>关联词条:</td><td><input type='text' name='input0' id='input0' value=''></td><td><input type='button' value='清空' onclick=\"clearInput('input0' )\"></td></tr>" + tableTr
+ "<tr><td></td><td><input type='button' value='提交' onclick=\"packageParam('" + flag + "','" + id + "','" + title + "','" + name + "','" + url + "','" + date
+ "')\"></td><td></td></tr></table>";
giftShopTool.HDdialog("关联词条编辑窗", html, 300, 260);
initKeyWord();
} /**
* 清空提交表单
*
* @param inputId
*/
function clearInput(inputId) {
$("#" + inputId).val("");
}
/**
* 封装參数
*
* @param flag
* @param id
* @param title
* @param name
* @param url
* @param date
*/
function packageParam(flag, id, title, name, url, date) {
var models = "";
var docTitles = "";
// 封装model
if (flag == "single") {
models = singleRelateDoc(id, title, name, url, date);
} else if (flag == "complex") {
models = complexRelateDoc();
}
// 封装词条名
for ( var i = 0; i < 10; i++) {
var docTitle = $("#input" + i).val();
if (docTitle != "") {
docTitles += docTitle + ";";
}
}
if (models == "" || models == "[]") {
alert("至少须要选择一个新闻! ");
} else if (docTitles == "") {
alert("至少须要关联一个词条名!");
} else {
relateDoc(models, docTitles)
}
}
/**
* 关联单个词条
*
* @param models
* @param docTitles
*/
function relateDoc(models, docTitles) {
$.ajax({
dataType : 'json',
type : 'POST',
url : '/baikeArchive.do? action=relateDoc',
data : {
"models" : models,
"docTitles" : docTitles
},
success : function(data) {
alert(data.msg);
window.location.href = "/baikeArchive.do?action=show";
},
error : function() {
alert("因为网络问题。查看失败");
return false;
}
});
}</span>

2.页面引入

<span style="font-family:KaiTi_GB2312;font-size:18px;"><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core"%>
<!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=utf-8" />
<title>百科观察外部新闻查看</title>
<link rel="stylesheet" type="text/css" href="http://www.huimg.cn/app/baikesurvey/css/baikeSurveyCSS.css" />
<script type="text/javascript" src="http://www.huimg.cn/lib/jquery-1.7.min.js"></script>
<script src="http://www.huimg.cn/lib/jquery.dialog-0.8.min.js? 10131624" type="text/javascript"></script>
<script type="text/javascript" src="http://www.huimg.cn/app/baikesurvey/js/baikeSurveyOuterNews20140521.js"></script>
</head>
<body> <form id="serachForm" action="/baikeSurvey.do?action=searchOutherNews&id=${ baikeSurvyId }" method="post">
<div class="search-s">
<span style="font-size: 13px;color:orange;">注意:输入的关键词中不能包括,和,(中英文逗号)</span></br>
关键词:
<input type="text" class="inpt" id="searchKeyword1" name="searchKeyword1" value="${searchKeyword1}" />
<input type="text" class="inpt" id="searchKeyword2" name="searchKeyword2" value="${searchKeyword2}" />
<input type="text" class="inpt" id="searchKeyword3" name="searchKeyword3" value="${searchKeyword3}" />
<input type="text" class="inpt" id="searchKeyword4" name="searchKeyword4" value="${searchKeyword4}" />
<input type="text" class="inpt" id="searchKeyword5" name="searchKeyword5" value="${searchKeyword5}" /></br>
</div></br>
<div class="search-q">
<input type="submit" class="btn-b" value="查询新闻" />     <input type="button" onclick="showRelateDocPage('complex')"class="btn-b" value="关联词条"/>
</div>
</form><br>
<span style="font-size: 13px;color:orange;margin-left: 25px;">提示:标红的新闻标题说明已存在百科档案</span></br>
<div class="slist">
<form id="submitForm" action="/baikeSurvey.do? action=showText" method="post">
<table>
<tr>
<th width="100"><input type="checkbox" name="selectNews" id="checkAll" onclick="selectAll()">全选</th>
<th width="110">外部新闻id</th>
<th>外部新闻标题</th>
<th width="250">操作</th>
</tr>
<c:if test="${count > 0 }">
<c:forEach var="model" items="${outerNewsTitleList}">
<tr topTr='${model.id}' >
<td><input type="checkbox" name="outerNewsId" value="${model.id}" ></td>
<td><span id="id${model.id}">${model.id}</span></td>
<td><a href="${model.outerNewsURL}" title="${model.outerNewsTitle}" id="title${model.id}" target="_blank" style="color:${model.color}">${model.outerNewsTitle}</a></td>
<input type="hidden" name="outerNewsSiteName" id="name${model.id}" value="${ model.outerNewsSiteName }"/>
<input type="hidden" name="outerNewsSiteUrl" id="url${model.id}" value="${ model.outerNewsSiteUrl }"/>
<input type="hidden" name="outerNewsDate" id="date${model.id}" value="${ model.outerNewsDate }"/>
<td><a href="#" onclick="javascript:findOuterNews('${model.id}');">查看正文</a> |
<a href="#" onclick="javascript:showRelateDocPage('single','${model.id}','${model.outerNewsTitle}','${ model.outerNewsSiteName }','${ model.outerNewsSiteUrl }','${ model.outerNewsDate }');">关联词条</a></td>
</tr>
</c:forEach>
</c:if>
<c:if test="${count < 1 }">
<tr>
<td align="center" nowrap="nowrap" colspan="11"><font style='font-weight:bolder;' color='red'>暂无相关数据</font></td>
</tr>
</c:if>
</table>
<div class="page-navi">共计 ${count} 条</div>
<c:if test="${pagePanel != null}">
<div class="page-navi">${pagePanel}</div>
</c:if>
<!-- 从外部新闻搜索页将百科观察的id传入百科观察正文页 -->
<input type="hidden" name="id" id="id" value="${ baikeSurvyId }"/>
</form>
</div> </body>
</html></span>

3.相关的action处理

1.搜索操作

<span style="font-family:KaiTi_GB2312;font-size:18px;"> /**
* 搜索显示外部新闻列表页数据 add by yangkai
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward searchOutherNews(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { List<String> listStr = new ArrayList<String>();
String baikeSurvyId = ServletRequestUtils.getSingleStringParameter(request, "id", ""); // 百科观察id
// 查询条(输入文本框值)
StringBuffer sbKeyword = new StringBuffer();
for (int i = 1; i < 6; i++) {
String keyword = ServletRequestUtils.getSingleStringParameter(request, "searchKeyword" + i, "");
if (StringUtils.isNotBlank(keyword)) {
if (keyword.contains(",") || keyword.contains("。")) {
request.setAttribute("err_msg", "输入的參数不合法:关键词中不能包括,和,");
return mapping.findForward("error");
}
if (i > 1 && i < 6) {
sbKeyword.append(",");
}
listStr.add(keyword);
sbKeyword.append(URLEncoder.encode(keyword, "utf-8"));
// 回显查询条件
request.setAttribute("searchKeyword" + i, keyword);
}else{
break;
}
}
String pageNow = ServletRequestUtils.getSingleStringParameter(request, "pageNow", "1");
int pageNum = Integer.valueOf(pageNow);
PageList<OuterNewsBizModel> outerNewsTitleList = null;
String pagePanel = "";// 分页栏字符串
Integer count = 0; // 总页数
String searchKeyword = sbKeyword.toString();
if (StringUtils.isNotBlank(searchKeyword) && StringUtils.isNotEmpty(searchKeyword)) {
outerNewsTitleList = baikeSurveyManager.queryOuterNewsPageList(searchKeyword, pageNum, pageSize);
try {
if (null != outerNewsTitleList && outerNewsTitleList.size() > 0) {
Paginator paginator = outerNewsTitleList.getPaginator();
if (paginator != null) {
count = paginator.getItems();
if (pageNum > paginator.getPages()) {
pageNum = paginator.getPages();
}
StringBuffer param = new StringBuffer();
for (int i = 0; i < listStr.size(); i++) {
param .append("&searchKeyword" + (i+1) + "=").append(listStr.get(i));
}
pagePanel = HdDepartPageUtil.getdepartStr("/baikeSurvey.do?action=searchOutherNews" + param.toString() + "&id=" + baikeSurvyId, "pageNow", pageNum, paginator.getPages());
}
}
} catch (Exception e) {
request.setAttribute("err_msg", "訪问数据失败");
logger.error(HuDongErrorCodeEnum.ProgramError, "訪问外部新闻列表失败", e);
return mapping.findForward("error");
}
}
request.setAttribute("outerNewsTitleList", outerNewsTitleList);
request.setAttribute("pagePanel", pagePanel);
request.setAttribute("count", count);
request.setAttribute("baikeSurvyId", baikeSurvyId);
return mapping.findForward("outerNewsShow");
}</span>

2.关联操作,重点使用jsonObject传送參数

<span style="font-family:KaiTi_GB2312;font-size:18px;"> /**
* 外部新闻关联词条 add by yangkai
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward relateDoc(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
PrintWriter out = BaikeSurveyUtils.getPrintWriter(response);
try { // 获取參数
String models = ServletRequestUtils.getSingleStringParameter(request, "models", "");
String docTitles = ServletRequestUtils.getSingleStringParameter(request, "docTitles", "");
String[] docTitleStr = docTitles.split(";");
JSONArray jsonArray = new JSONArray(models);
StringBuffer result = new StringBuffer();
for (int i = 0; i < jsonArray.length(); i++) {
org.json.JSONObject jsonModel = jsonArray.optJSONObject(i);
for (String docTitle : docTitleStr) {
// 封装百科档案对象
BaikeArchiveDO baikeArchiveDO = new BaikeArchiveDO();
String outNewsId = jsonModel.get("id").toString();
String archiveTitle = jsonModel.get("title").toString();
baikeArchiveDO.setDocTitle(docTitle);
baikeArchiveDO.setArchive_title(archiveTitle);
baikeArchiveDO.setNewsnetname(jsonModel.get("name").toString());
baikeArchiveDO.setNewsnetnameurl(jsonModel.get("url").toString());
baikeArchiveDO.setEditNick(currentUserView.getUserNick());
baikeArchiveDO.setCreateNick(currentUserView.getUserNick());
Timestamp ts = Timestamp.valueOf(jsonModel.get("date").toString());
baikeArchiveDO.setCreateTime(ts);
baikeArchiveDO.setEditTime(ts);
baikeArchiveDO.setNewstime(ts);
baikeArchiveDO.setState(1);
baikeArchiveDO.setOutNewsId(outNewsId);
int pk = baikeArchiveManager.addBaikeArchiveDO(baikeArchiveDO);
if (pk > 0) {
String archiveContent = baikeSurveyManager.findOuterNewsTextById(Integer.parseInt(outNewsId));
boolean flag = editOuterArchiveText(String.valueOf(pk), archiveContent, archiveTitle, currentUserView);
if (flag) {
result.append("ID为" + outNewsId + "的新闻").append("关联" + docTitle + "成功").append(";\r\n");
} else {
result.append("ID为" + outNewsId + "的新闻").append("关联" + docTitle + "失败").append(";\r\n");
}
dealBaikeSurveyTitleWidget(String.valueOf(pk), docTitle, "");
logger.info("关联词条成功 : 百科标题= " + jsonModel.get("title").toString());
}
}
}
BaikeSurveyUtils.responseStr(out, BaikeSurveyUtils.createJsonObject("1", result.toString()));
} catch (Exception e) {
logger.error(HuDongErrorCodeEnum.ProgramError, "关联词条失败", e);
BaikeSurveyUtils.responseStr(out, BaikeSurveyUtils.createJsonObject("0", "关联词条失败!"));
return null;
} return null;
}</span>

4.相关业务处理

1.核心业务处理

<span style="font-family:KaiTi_GB2312;font-size:18px;">    /**
* 封装外部新闻list方法
*/
@Override
public PageList<OuterNewsBizModel> queryOuterNewsPageList(String searchKeyword, Integer pageNo, Integer pageSize) { // 声明參数
List<OuterNewsBizModel> modelList = new ArrayList<OuterNewsBizModel>();
StringBuffer outNewsIdSb = new StringBuffer(); // in 条件
Map<String, Integer> flag = new HashMap<String, Integer>(); // 对照list的标识
List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
PageList<OuterNewsBizModel> pageList = new PageList<OuterNewsBizModel>();
Paginator paginator = new Paginator();
net.sf.json.JSONObject jsonObjectTotle = null; // 1.封装分页參数
try {
Map<String, Object> paraMap = new HashMap<String, Object>();
paraMap.put("pageNum", (pageNo - 1) * pageSize);
paraMap.put("pageSize", pageSize);
paginator.setItemsPerPage(pageSize);
paginator.setPage(pageNo);
pageList.setPaginator(paginator);
} catch (Exception e) {
logger.error(HuDongErrorCodeEnum.ProgramError, "封装外部新闻list方法[封装分页參数异常]:", e);
}
try {
String phpSearchUrl = Constants.PHP_SEARCH_URL;
StringBuffer url = new StringBuffer(StringUtils.EMPTY);
url.append(phpSearchUrl).append("?keyword=").append(searchKeyword).append("&page=").append(pageNo).append("&size=").append(pageSize).append("&t=" + System.currentTimeMillis());
String jsonString = sendRequest(url.toString());
jsonObjectTotle = net.sf.json.JSONObject.fromObject(jsonString);
String state = net.sf.json.JSONObject.fromObject(jsonObjectTotle.get("state")).get("code").toString();
if (("0").equals(state)) {
String news = net.sf.json.JSONObject.fromObject(jsonObjectTotle.get("data")).get("news").toString();
org.json.JSONArray jsonArrays = new org.json.JSONArray(news); for (int i = 0; i < jsonArrays.length(); i++) {
Map<String, Object> map = new HashMap<String, Object>();
JSONObject outerNewsObject = jsonArrays.getJSONObject(i);
OuterNewsBizModel outerNews = new OuterNewsBizModel();
String outNewsId = outerNewsObject.get("id").toString();
String time = outerNewsObject.get("news_date").toString();
// 封装外部新闻对象
outerNews.setId(Integer.parseInt(outNewsId));
outerNews.setOuterNewsTitle(outerNewsObject.get("title").toString());
outerNews.setOuterNewsURL(outerNewsObject.get("url").toString());
outerNews.setOuterNewsSiteName(outerNewsObject.get("site_name").toString());
outerNews.setOuterNewsSiteUrl(outerNewsObject.get("site_url").toString());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(Long.valueOf(time.concat("000")));
String dateTime = df.format(date);
outerNews.setOuterNewsDate(Timestamp.valueOf(dateTime)); flag.put(outNewsId, 1);
// 封装in查询条件
outNewsIdSb.append("'" + outNewsId + "'");
if (i < jsonArrays.length() - 1) {
outNewsIdSb.append(",");
}
map.put("outerNews", outerNews);
map.put("color", "#015FBF"); // 显示样式,默觉得蓝色
listMap.add(map);
}
} else {
String msg = net.sf.json.JSONObject.fromObject(jsonObjectTotle.get("state")).get("msg").toString();
logger.info("[调用php search接口返回错误]", msg);
return null;
}
} catch (Exception e) {
logger.error(HuDongErrorCodeEnum.ProgramError, "封装外部新闻list方法[拼装业务model与调用php接口异常]:", e);
}
// 3.推断词条是否已存在百科档案
try {
List<BaikeArchiveRelationDO> listRels = this.baikeArchiveReadDAO.checkBaikeArchiveOutNews(outNewsIdSb.toString()); // 查找百科档案关系表
if (listRels != null && listRels.size() > 0) {
for (BaikeArchiveRelationDO baikeRelDO : listRels) { // 存在百科档案的将其值改为2
String outId = baikeRelDO.getOutNewsId();
if (flag.get(outId) != null) {
flag.put(outId, 2);
}
}
}
} catch (Exception e) {
logger.error(HuDongErrorCodeEnum.ProgramError, "封装外部新闻list方法[验证百科档案存在]:", e);
} // 4.封装终于页面展示的分页list
try {
for (Map<String, Object> map : listMap) {
String color = map.get("color").toString();
OuterNewsBizModel outerNews = (OuterNewsBizModel) map.get("outerNews");
if (flag.get(outerNews.getId()+"").equals(2)) {
color = "red"; // 假设存在涨姿势,样式设置成红色
}
outerNews.setColor(color);
modelList.add(outerNews);
}
if (null != modelList && modelList.size() > 0) {
pageList.addAll(modelList);
String total = net.sf.json.JSONObject.fromObject(jsonObjectTotle.get("data")).get("total").toString();
paginator.setItems(Integer.valueOf(total));
}
} catch (Exception e) {
logger.error(HuDongErrorCodeEnum.ProgramError, "查询top1000词条记录业务层异常[封装终于list]:", e);
}
return pageList;
}</span>

2.一个跨语言的http接口方法

<span style="font-family:KaiTi_GB2312;font-size:18px;">  /**
* 訪问php接口
*
* @param url
* @return
*/
private static String sendRequest(String url) {
InputStream inputStream = null;
GetMethod getMethod = null;
try {
//url = chineseToUtf8(url);
getMethod = new GetMethod(url);
int statusCode = 0;
statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
logger.debug("訪问目标url:{0} 失败,http状态码:{1}", new Object[] { url, statusCode });
return StringUtils.EMPTY;
}
inputStream = getMethod.getResponseBodyAsStream();
if (inputStream == null) {
logger.debug("訪问目标url:{0} 失败,返回io流为空", new Object[] { url });
return StringUtils.EMPTY;
}
return IOUtils.toString(inputStream, "UTF-8");
} catch (HttpException e) {
logger.error(HuDongErrorCodeEnum.RemoteRequestError, "网络原因,訪问目标url:" + url + "失败", e);
return StringUtils.EMPTY;
} catch (IOException e) {
logger.error(HuDongErrorCodeEnum.RemoteRequestError, "io原因,訪问目标url:" + url + "失败", e);
return StringUtils.EMPTY;
} catch (Exception e) {
logger.error(HuDongErrorCodeEnum.RemoteRequestError, "訪问目标url:" + url + "失败", e);
return StringUtils.EMPTY;
} finally {
if (getMethod != null) {
getMethod.releaseConnection();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}</span>

5.扩展说明,兼容IE处理

使用jsonObject传送数据的时候,会存在ie7、8不兼容的问题。不支持json的stringify 方法。网上有一些兼容处理,认为不错的有:IE下JSON 没有定义

方法1、设置兼容模式:

IE8和IE9中都能正常执行(大概是IE8和IE9都提供了原生的JSON解析和序列化)

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

方法2、引用json2.js文件到页面

http://www.json.org/

搜索 json2.js,下载压缩包

把json2.js引入到页面,就OK了。

官网地址:https://github.com/douglascrockford/JSON-js/

<script type="text/javascript" src="/Scripts/json2.js"></script>

方法3、推断当前浏览器是否支持JSON对象。假设不支持。则引入json2.js文件---没试成功

if(typeof JSON == 'undefined'){

                $("head").append($("<script type='text/javascript' src='../Js/json2.js'></script>"));

            }



官网地址一般都非常难找到下载的入口,目測了下好像仅仅有把下copy的可能。这里提供一个下载地址:

json2下载地址:http://download.csdn.net/detail/tianyazaiheruan/7421331

版权全部:杨凯专属频道

转载请指明出处:http://blog.csdn.net/yangkai_hudong/article/details/27538541

版权声明:本文博主原创文章,博客,未经同意不得转载。