Ajax跨域请求——jsonp获取json数据

前端:后台有时候的得不到传来的参数,在ajax里加上data{"jsonpCallback":jsonpCallback}

		$.ajax({
			type:'POST',
			url:  'www.xxx.com/goods/countGoodsNumByCategoryId.json',
			data:{"categoryId":id},
			dataType:'jsonp',
			async:false,
			jsonp:'jsonpCallback',//传递给后台程序,用来获取jsonp回调函数名的参数名
			success:function(data){
				var isExistGoods = data.isExistGoods;
				var isNeedChooseCategory = data.isNeedChooseCategory;
				if(isExistGoods == 1){
					alertMsg.error("该类目下已存在商品,不能删除!");
				}
				if(isNeedChooseCategory == 1){
					alertMsg.error("请选择一个类目!");
				}
			},
			error:function(){
				alertMsg.error("该类目下已存在商品,不能删除!");
			}
		});


            $.ajax({
			type : "GET",//请求方式 get/post
			url : "http://" + tomcatBase + "/ilive/app/room/vod/checklogin.jspx",
			dataType : "jsonp",
			jsonp : "callback",
			cache : false,
			data : {
				fileId:fileId,
				roomId:roomId
			},
			success : function(data) {

后台:

	@RequestMapping({ "/countGoodsNumByCategoryId.json" })
	public void countGoodsNumByCategoryId(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("text/plain");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		Long categoryId = null;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String categoryIdJson = request.getParameter("categoryId");
		if (StringUtils.isNotBlank(categoryIdJson)) {
			categoryId = Long.parseLong(categoryIdJson);
			paramsMap.put("categoryId", categoryId);
			int goodsNum;
			try {
				goodsNum = goodsService.selectCount(paramsMap);
				if (goodsNum > 0) {
					resultMap.put("isExistGoods", BoolStatus.YES);
				} else {
					resultMap.put("isExistGoods", BoolStatus.NO);
				}
			} catch (ServiceException e) {
				LOG.error(e.getMessage(), e);
				resultMap.put("isExistGoods", BoolStatus.YES);
			}
		} else {
			resultMap.put("isNeedChooseCategory", BoolStatus.YES);
		}
		try {
			PrintWriter out = response.getWriter();
			JSONObject resultJSON = JSONObject.fromObject(resultMap); // 根据需要拼装json
			String jsonpCallback = request.getParameter("jsonpCallback");// 客户端请求参数
			out.println(jsonpCallback + "(" + resultJSON.toString(1, 1) + ")");// 返回jsonp格式数据
			out.flush();
			out.close();
		} catch (IOException e) {
			LOG.error(e.getMessage(), e);
		}
	}

猜你喜欢

转载自blog.csdn.net/atongmu2017/article/details/82896369