$.getjson()跨域问题,笔记

来源:互联网 发布:淘宝透明睡衣买家秀 编辑:程序博客网 时间:2024/05/29 19:34

经常边学边忘,整理记点笔记,以便复习。

1、

$.getJSON(host + api + "?jsoncallback=?", param, callback);

        host:"http://192.168.1.179:8080"

        api:"/Ddcxj/login/sdhloging.do"

        param:{username: 'sy11'}

        callback是返回函数,不要带括号

2、

后台接口的java代码:

       使用Servlet 的 request.getParameter("jsoncallback");获取callback,"jsoncallback"和$.getjson中url的"?jsoncallback=?"要

HttpServletResponse response 指定编码格式,response.getWriter().print(callback + "(" + result + ");");

@Controller@RequestMapping("/tongzhi/")public class TongZhiController {    public SDTongZhiService tongZhiService=new SDTongZhiServiceImpl();    @RequestMapping("getmessage")    @ResponseBody    public void getmessage(String userid,HttpServletRequest request, HttpServletResponse response) throws IOException{                 List<Map<String, Object>>  ret=null;            try {                ret=tongZhiService.getmessage(userid);            } catch (Exception e) {                // TODO: handle exception                e.printStackTrace();            }            JSONObject jsonObject = new JSONObject();            JSONObject result=jsonObject.accumulate("result", ret);            String callback = request.getParameter("jsoncallback");// jquery生成的自定义函数名            response.setCharacterEncoding("UTF-8");            response.setContentType("text/html;charset=utf-8");            response.getWriter().print(callback + "(" + result + ");");    }
3、

json数据格式要求比较严格,key和value都必须引号括起来,下面是测试数据:

                JSONObject jsonObject = new JSONObject();JSONObject dataEle1 = new JSONObject();dataEle1.put("name", "张三");dataEle1.put("age", "23");dataEle1.put("sex", "男");JSONObject dataEle2 = new JSONObject();dataEle2.put("name", "李三");dataEle2.put("age", "20");dataEle2.put("sex", "女");JSONArray jsonArray = new JSONArray();jsonArray.add(dataEle1);jsonArray.add(dataEle2);// jsonObject.accumulate("data", jsonArray);jsonObject.element("data", jsonArray);


0 0
原创粉丝点击