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

本文介绍了JSONP实现跨域请求的原理,并通过一个具体的示例展示了如何使用jQuery发起JSONP请求,同时提供了服务器端响应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()+""); 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值