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

前端之家收集整理的这篇文章主要介绍了Ajax跨域请求——jsonp获取json数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

JSONP(JSON with Padding)是JSON的一种“使用模式”,可用于解决主流浏览器的跨域数据访问的问题;

例如在同一个系统中,我们进行了分布式分域名的部署,但是在这个域里面,我们需要通过ajax的方式去访问获取另一个域的数据,这时就产生的跨域的请求,但是浏览器出去安全考虑,是不允许进行跨域请求的;

json与jsonp的区别:json是一种数据传输格式,而jsonp则是数据传输的协议或者是说方式。

直接码代码

前端页面使用jquery进行ajax请求,当然使用js进行ajax请求的可以自行对应修改

  1. $.ajax({
  2. type:'POST',url: 'www.xxx.com/goods/countGoodsNumByCategoryId.json',data:{"categoryId":id},dataType:'jsonp',async:false,jsonp:'jsonpCallback',//传递给后台程序,用来获取jsonp回调函数名的参数名
  3. success:function(data){
  4. var isExistGoods = data.isExistGoods;
  5. var isNeedChooseCategory = data.isNeedChooseCategory;
  6. if(isExistGoods == 1){
  7. alertMsg.error("该类目下已存在商品,不能删除!");
  8. }
  9. if(isNeedChooseCategory == 1){
  10. alertMsg.error("请选择一个类目!");
  11. }
  12. },error:function(){
  13. alertMsg.error("该类目下已存在商品,不能删除!");
  14. }
  15. });
我们的dataType必须为jsonp,然后比以往常规的ajax请求多了一个jsonp参数,这个参数是用来获取后台服务端返回的数据的;



服务端java代码

  1. @RequestMapping({ "/countGoodsNumByCategoryId.json" })
  2. public void countGoodsNumByCategoryId(HttpServletRequest request,HttpServletResponse response) {
  3. response.setContentType("text/plain");
  4. response.setHeader("Pragma","No-cache");
  5. response.setHeader("Cache-Control","no-cache");
  6. response.setDateHeader("Expires",0);
  7. Map<String,Object> paramsMap = new HashMap<String,Object>();
  8. Long categoryId = null;
  9. Map<String,Object> resultMap = new HashMap<String,Object>();
  10. String categoryIdJson = request.getParameter("categoryId");
  11. if (StringUtils.isNotBlank(categoryIdJson)) {
  12. categoryId = Long.parseLong(categoryIdJson);
  13. paramsMap.put("categoryId",categoryId);
  14. int goodsNum;
  15. try {
  16. goodsNum = goodsService.selectCount(paramsMap);
  17. if (goodsNum > 0) {
  18. resultMap.put("isExistGoods",BoolStatus.YES);
  19. } else {
  20. resultMap.put("isExistGoods",BoolStatus.NO);
  21. }
  22. } catch (ServiceException e) {
  23. LOG.error(e.getMessage(),e);
  24. resultMap.put("isExistGoods",BoolStatus.YES);
  25. }
  26. } else {
  27. resultMap.put("isNeedChooseCategory",BoolStatus.YES);
  28. }
  29. try {
  30. PrintWriter out = response.getWriter();
  31. JSONObject resultJSON = JSONObject.fromObject(resultMap); // 根据需要拼装json
  32. String jsonpCallback = request.getParameter("jsonpCallback");// 客户端请求参数
  33. out.println(jsonpCallback + "(" + resultJSON.toString(1,1) + ")");// 返回jsonp格式数据
  34. out.flush();
  35. out.close();
  36. } catch (IOException e) {
  37. LOG.error(e.getMessage(),e);
  38. }
  39. }

上面这个代码片段,有些是我自己进行了工具类封装的,根据意思大家就能明白是起什么作用的。

返回数据是通过response的流来进行直接返回的,这里从request中间获取了一个jsonpCallback,这个跟我们的前台ajax那个jsonp参数是对应的,大家可以自行修改成自己喜欢的名称

然后这样我们就完成了,跨域情况下的ajax请求。

猜你在找的Ajax相关文章