JS跨域:2.解决方案之-设置回调参数

一 服务器端代码

package com.cn;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/data/inteface")
public class CSDNTest {
    @RequestMapping("/getdata")
    public void getSolrArticleen(String parameter,
            HttpServletRequest request, HttpServletResponse response) throws Exception{
        String callback = request.getParameter("jsoncallback");
        parameter = new String(parameter.getBytes("iso-8859-1"), "utf-8");
        //获取数据
        DataRepository dataRepository = new DataRepository();
        List<String> primaryItems = dataRepository.getData();
        //把获取的数据转换成字符串,这里用的是FastJson,也可以根据需要用Gson
        String jsonArticle = JSONObject.toJSONString(primaryItems,
                SerializerFeature.DisableCircularReferenceDetect);
        //把需要输出的服务器端的字符串拼接callback头     
        String json = callback+"(" + jsonArticle + ")";
        //输出到客户端
        GetOut.getWriter(json, response);
    }
}

  

二 获取输出流的代码

package com.cn;


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
/**
 * 
 * @Title: GetOut.java
 *
 * @Package: com.cn
 *
 * @Company: WiiMedia
 *
 * @Description: 获取输出流
 *
 * @author: SongJia
 *
 * @date: 2016-06-27 上午11:09:27
 *
 */
public  class GetOut {
    public static PrintWriter getWriter(String msg,HttpServletResponse response) throws IOException{
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = null;
        out = response.getWriter();
        out.write(msg);
        out.flush();
        out.close();
        return out;
    }
}

  

三 客户端请求数据代码

<script type="text/javascript">
    function AcquireData() {
        $.ajax({   
            async:false,   
            url: "http://m.lecoonginfo.com/data/inteface/getdata,  // 跨域URL  
            type: 'GET',   
            dataType: 'jsonp',   
            jsonp: 'jsoncallback', //默认callback  
            timeout: 5000,   
                success: function (json) {
                 //客户端jquery预先定义好的callback函数,
                 //成功获取跨域服务器上的json数据后,
                 //会动态执行这个callback函数   
                console.log(json);
                }
            }
        });   
</script>

  

 

转载于:https://www.cnblogs.com/Matchman/p/7380042.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值