首页 > 技术文章 > 使用jsonp进行跨域访问

always-online 2014-07-21 22:11 原文

一、使用场景

  当我们请求非本服务器的资源的时候,浏览器会禁止访问,并提示不允许跨域访问。此时我们可以使用jsonp这种请求方式,从其他服务器获取资源。在客户端调用提供jsonp支持的接口,获取jsonp格式的数据。

二、客户端的实现

  客户端使用jsp,用js发送ajax请求,代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <base href="<%=basePath%>">
        <title>jsonp</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <script type="text/javascript" src="./js/jquery-1.9.1.min.js"></script>
</head>
<body>
        <script type="text/javascript">
jQuery(document).ready(function() {

    $.ajax( {
        type : "get",
        async : false,
        url : "http://127.0.0.1:8089/test2/TestServlet?id=1",
        dataType : "jsonp",
        jsonp : "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
        jsonpCallback : "Tcallback",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
        success : function(json) {
            alert('name: ' + json.name + ',age: ' + json.age);
        },
        error : function() {
            alert('fail');
        }
    });

});
</script>
</body>
</html>

 

  此段代码相当于get请求http://127.0.0.1:8089/test2/TestServlet?id=1&callback=Tcallback .

三、服务器实现

  服务器端使用servlet实现,代码如下:

public class TestServlet extends HttpServlet
{

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        String id = request.getParameter("id");
        String callback = request.getParameter("callback");//值为Tcallback 
        String name = "zhangsan";
        int age = 20;
        String json = String.format("%s({\"name\":\"%s\", \"age\":%s})",
                callback, name, age);//返回的数据
        PrintWriter out = response.getWriter();
        out.print(json);
        out.flush();
        out.close();
    }
}

推荐阅读