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>

  

 

posted @ 2017-08-17 09:55  MatrixDemiurge  阅读(251)  评论(0编辑  收藏  举报