AngularJS $http.jsonp 跨域的问题

1、官方API给出的方法

jsonp(url, [config]);

Shortcut method to perform JSONP request.

Parameters

Param Type Details
url string Relative or absolute URL specifying the destination of the request. The name of the callback should be the string JSON_CALLBACK.
config

(optional)
Object Optional configuration object

Returns

HttpPromise Future object


2、使用方法示例
$http.jsonp("http://192.168.1.56:8080/qyhaomarket/goods/list?callback=JSON_CALLBACK").success(function(data){
       angular.fromJson(data);//转换为JSON
       console.log(angular.fromJson(data)[0].img);
   }).error(function(data, status){
       console.log(status);
   });
注意:此处的callback参数很重要,后台接收callback的值,根据接收callback的值调用回调函数,传递JSON数据
服务端的返回参数格式:
JSON_CALLBACK([
    {"id": "1", "name": "John Doe"},
    {"id": "2", "name": "Lorem ipsum"},
    {"id": "3", "name": "Lorem ipsum"}
]);
3、服务端的数据处理
 
接收客户端的请求参数:
[callback:angular.callbacks._0, action:list, format:null, controller:goods]
 
可以看到callback的参数值是angular.callbacks._0 这个是回调函数,要根据它来返回JSON数据。
Groovy的使用
def datas = [["id":"1","name": "John Doe"], ["id": "2", "name": "Lorem ipsum"],  ["id": "3", "name": "Lorem ipsum"]]

render (text:"${params.callback}(${datas as JSON})",contentType: "text/plain", status:response.SC_OK)

Servlet中的使用:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json;charset=UTF-8");
    PrintWriter out = resp.getWriter();
    String callbackFunName = req.getParameter("callback");
    StringBuilder stringBuilder = new StringBuilder(callbackFunName);
    stringBuilder.append("(");
    stringBuilder.append("{'id':'1','name': 'John Doe'}");
    stringBuilder.append(")");
    out.println(stringBuilder.toString());
    out.print(result);
    out.flush();
    out.close();
}

6 Comments

博主网站相当的不错哦,希望以后多多交流,欢迎来我的小站逛逛http://www.panguanqi.com

文章很不错哦,对我的学习很有帮助

jsonp 跨域的问题,纠结了很久

难得好贴,赞一个,继续努力啊

真的吗?太好了,非常喜欢

Leave a Reply

Your email address will not be published.