zoukankan      html  css  js  c++  java
  • 使用jsonp进行跨域访问

    一、使用场景

      当我们请求非本服务器的资源的时候,浏览器会禁止访问,并提示不允许跨域访问。此时我们可以使用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();
        }
    }
  • 相关阅读:
    两数之和
    IntelliJ IDEA为类和方法自动添加注释
    IDEA main 函数的快捷键
    Mac终端开启代理
    Pycharm节能模式
    使用正则表达式替换构造字典
    使用代理爬取微信文章
    利用 Scrapy 爬取知乎用户信息
    Scrapy选择器的用法
    Scrapy命令行基本用法
  • 原文地址:https://www.cnblogs.com/always-online/p/3859340.html
Copyright © 2011-2022 走看看