jQuery jsonp跨域请求封装函数

如下所示为jsonp跨域请求封装的的ajax代码:

详细解释参看:https://blog.csdn.net/guanmao4322/article/details/88782995

 $(document).ready(function () {
     $("#btn").click(function () {
         $.ajax({
               url: "http://localhost:9090/student",//访问路径
               type: "GET",
               dataType: "jsonp",  //指定服务器返回的数据类型
               jsonp: "callback",   //指定参数名称
               jsonpCallback: "showData",  //指定回调函数名称
           });
       }
 });
//回调函数
function showData (data) {
    console.info("调用showData");
    var result = JSON.stringify(data);
    $("#text").val(result);
}

服务器端:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");

    // * 表示允许任何域名跨域访问
    response.setHeader("Access-Control-Allow-Origin", "*");
    // 指定特定域名可以访问
    //response.setHeader("Access-Control-Allow-Origin", "http:localhost:8080/");

    //数据
    List<Student> studentList = getStudentList();

    JSONArray jsonArray = JSONArray.fromObject(studentList);
    String result = jsonArray.toString();

    //前端传过来的回调函数名称
    String callback = request.getParameter("callback");
    //用回调函数名称包裹返回数据,这样,返回数据就作为回调函数的参数传回去了
    result = callback + "(" + result + ")";

    response.getWriter().write(result);
}

注:在HTML页面中注意引入jQuery.js

 

参考:https://www.cnblogs.com/chiangchou/p/jsonp.html,表示感谢!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值