Ajax实现跨域访问

前台写法:

function searchByWord(){

 $.ajax({
                type:'get',//这里必须使用get方法
                async: false,
                url:"XXXXXXXX",
                dataType:'jsonp',  // JSONP处理Ajax跨域问题
                jsonp:'callbackparam',  
                 data:{'word':encodeURI(word)},
                 jsonpCallback:"success_jsonpCallback",  
                 success: function(data){   }
            });  
    }
后台写法:

// 提供接口,返回问题类型JSON
        @RequestMapping("/XXXX")
        public void searchWechat(Integer pagenum,HttpServletRequest request,HttpServletResponse response)
                throws Exception {
            response.setContentType("text/plain");  
            response.setCharacterEncoding("UTF-8");   
            String callbackFunName=request.getParameter("callbackparam");
            String word=request.getParameter("word");
            word = URLDecoder.decode(word, "utf-8");
            String userid = null;
            if (getCurrentUser(request.getSession()) != null) {
                userid = getCurrentUser(request.getSession()).getId();
            }
            if (word == null) {
                word = "";
            }
            
              try {
                  DataResult  result = farmDocIndexManagerImpl.search(word, userid, pagenum);
                    response.getWriter().write(callbackFunName + "("+JSONObject.fromObject(result)+")"); //返回jsonp数据
                } catch (Exception e) {
                    e.printStackTrace();
                }
              
            
        }

猜你喜欢

转载自blog.csdn.net/cacalili/article/details/79096605