使用jquery跨域获取json

@先打标签


1 示例

js代码

//第一个是url  第二个是请求参数   最后是回调结果数据   ?jsoncallback=?
    $.getJSON("http://localhost:8080/CRWeb/tryinit?jsoncallback=?", function(json){
        console.log(json);  
    });

servlet代码

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("received");
        
        //获取json的占位符内容
        String callbackName = (String) request.getParameter("jsoncallback");
        System.out.println(callbackName);
                
        Person p = new Person();
        p.setName("isme");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("data", JSON.toJSON(p)); //这里使用的是fastjson
        map.put("code", 1);
        map.put("msg", "ok");
        
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(callbackName+"("+JSON.toJSONString(map) +")");
        System.out.println("ok");
    }

2 坑

服务器 代码已经给出来了,接着说下要注意的地方.

1 jquery的get和post是不能跨域请求的
  可能会出现 not allowed access
 2 服务器的servlet也要修改成支持jsonp
   最开始,我也像写普通servlet一样返回数据,浏览器可以访问,但是在js中总是出问题,在网上找到了解决方案 参考这个内容,有详细的解释,只是有一个获取attribute要修改下

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容