后台controller支持jsonp格式请求的样例

jsonp的原理:

       ajax请求受同源策略影响,不允许进行跨域请求,而script标签src属性中的链接却可以访问跨域的js脚本,利用这个特性,服务端不再返回JSON格式的数据,而是返回一段调用某个函数的js代码,在src中进行了调用,这样实现了跨域。

js中

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            type : "get",
            async: false,
            url : "http://www.practice-zhao.com/student.php?id=1",
            dataType: "jsonp",
            jsonp:"callback", //请求的参数名
            jsonpCallback: "jsonhandle",//要执行的回调函数
            success : function(data) {
                alert("age:" + data.age + "name:" + data.name);
            }

        });
    });
</script>

后台controller

@RequestMapping(value = "/systemTime")
public void systemTime(HttpServletRequest request,HttpServletResponse response) throws Exception {
   PrintWriter out = response.getWriter();
   response.setContentType("text/plain");
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Access-Control-Allow-Origin", "*");//添加跨域访问
    Result<String> result = new Result<String>(false);
    result.setCode("000000");
    result.setData(System.currentTimeMillis()+"");
    result.setMessage("success");
    result.setRight(true);
    result.setRlt(true);
    result.setSuccess(true);
    net.sf.json.JSONObject resultJSON = net.sf.json.JSONObject.fromObject(result); //根据需要拼装json   
    String jsonpCallback = request.getParameter("callback");//客户端请求参数
    out.println(jsonpCallback+"("+resultJSON.toString(1,1)+")");//返回jsonp格式数据  
    //writer.write(System.currentTimeMillis()+""); 
}

猜你喜欢

转载自blog.csdn.net/mazhenxing0805/article/details/79833503