使用JSONP进行跨域请求

JSP页面的ajax:

  $.ajax({ // get pagedata
            type : "post",
            url : treasureBaseURL2,
            dataType : "jsonp",
            data : {productId : 123, userMobile : '12324'},
            jsonp : "callbackparam",
            jsonpCallback : "success_jsonpCallback",
            success : function(data) {
                var object = eval(data[0].result);
                $(object).each(function(index) {
                    alert(object[index].treasureCode);
                });
            },
            error : function() {
                alert('Error');
            }
        });

Controller中的Java:

  @RequestMapping(value = "/orderlist/{page}", produces="text/html;charset=UTF-8")
    public void search(@PathVariable(value = "page") Integer page, @ModelAttribute("formBean") AdminOrdersQueryFormBean formBean,HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        Page<AdminOrdersFormBean> data = new Page<AdminOrdersFormBean>();
        
        logger.info(page + "===admin===" + formBean.getProductId() + "," + formBean.getUserMobile());
        List<AdminOrdersFormBean> productFormBeans = getOrdersFormBeans();  // 获取数据
        
        data.setResult(productFormBeans);
        data.setPageNo(page);
        data.setPageSize(8);
        data.setTotalCount(22);
        
        String callbackFunName =request.getParameter("callbackparam");
        response.getWriter().write(callbackFunName + "([ " + JsonUtil.toJson(data) + "])");
    }
JsonUtil.java , Page.java

返回数据'data'示例:
success_jsonpCallback([ {"pageNo":1,"pageSize":8,"orderBy":null,"order":null,"autoCount":true,"result":[{"orderId":222,"parentId":null,"userId":null,"userName":"dada0","userMobile":"ddddd","treasureCode":"3123213,31313,3131","okCode":null,"cTime":"2015-12-14","productId":3131,"productTerm":3},{"orderId":223,"parentId":null,"userId":null,"userName":"dada1","userMobile":"ddddd","treasureCode":"3123213,31313,3131","okCode":null,"cTime":"2015-12-14","productId":3132,"productTerm":3}],"totalCount":22,"totalPages":3,"orderBySetted":false,"hasNext":true,"nextPage":2,"hasPre":false,"prePage":1,"first":1}])

 

posted @ 2015-12-14 16:51  Iamcui  阅读(2176)  评论(0编辑  收藏  举报