Jsonp(JSON with Padding) 是 json 的一种"使用模式",可以让网页从别的域名(网站)那获取资料,即跨域读取数据。
后台接口实现1:
// 查询试用产品分类
@GetMapping("/selectCategoryListByJsonP")
@ResponseBody
public Object selectCategoryListByJsonP(HttpServletRequest request, HttpServletResponse response,String mallId)throws IOException {
String str1=mallId.substring(0, mallId.indexOf("_"));
String str2=mallId.substring(str1.length()+1, mallId.length());
QueryResult queryResult = new QueryResult<>();
List<Map> list =new ArrayList<>();
if(str2.equals("00")){
list = categoryRepository.getCategoryByDepartmentIdAndCategoryParentGroupById(str1);
}
else{
list = mallProductRepository.getListGroupByCategory(mallId);
}
queryResult.setRecords(list);
String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数
String resultJSON = JSONObject.toJSONString(queryResult);
Object result=(StringUtils.isNotBlank(jsonpCallback) ? jsonpCallback : "jsonpCallback") + "(" + (resultJSON != null ? resultJSON : "") + ")";
log.info(result.toString());
return result;
}
2
// 查询试用产品分类
@GetMapping("/selectCategoryListByJsonP")
@ResponseBody
public void selectCategoryListByJsonP(HttpServletRequest request, HttpServletResponse response,String value)throws IOException {
response.setContentType("text/plain");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
String str1=value.substring(0, value.indexOf("_"));
String str2=value.substring(str1.length()+1, value.length());
QueryResult queryResult = new QueryResult<>();
List<Map> list =new ArrayList<>();
if(str2.equals("00")){
list = categoryRepository.getCategoryByDepartmentIdAndCategoryParentGroupById(str1);
}
else{
list = mallProductRepository.getListGroupByCategory(value);
}
queryResult.setRecords(list);
PrintWriter out = response.getWriter();
JSONObject resultJSON = JSONObject.parseObject(JSONObject.toJSON(queryResult).toString());//根据需要拼装json
String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数
out.println(jsonpCallback+"("+resultJSON+")");
out.flush();
out.close();
}
前台接收
$.ajax({
type:"get",
async:false,
url:"https://knmarket.cnki.net/knmarket-web/mallProduct/selectCategoryListByJsonP?value=116_00",
dataType:"jsonp",
jsonp:"jsonpCallback",
success:function(data){
alert("here::"+JSON.stringify(data))
},
error:function(errormsg){
alert("error")
}
})
网友评论