跨域,前端开发中经常遇到的问题,AngularJS实现跨域方式类似于Ajax,使用CORS机制。
下面阐述一下AngularJS中使用$http实现跨域请求数据。

AngularJS XMLHttpRequest:$http用于读取远程服务器的数据

$http.post(url, data, [config]).success(function(){ ... });
$http.get(url, [config]).success(function(){ ... });
$http.get(url, [config]).success(function(){ ... });

一、$http.jsonp【实现跨域】

1. 指定callback和回调函数名,函数名为JSON_CALLBACK时,会调用success回调函数,JSON_CALLBACK必须全为大写。
2. 指定其它回调函数,但必须是定义在window下的全局函数。url中必须加上callback。

二、$http.get【实现跨域】

1. 在服务器端设置允许在其他域名下访问

response.setHeader("Access-Control-Allow-Origin", "*"); //允许所有域名访问
response.setHeader("Access-Control-Allow-Origin", "http://www.123.com"); //允许www.123.com访问

2. AngularJS端使用$http.get()

三、$http.post【实现跨域】

1. 在服务器端设置允许在其他域名下访问,及响应类型、响应头设置

response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods","POST");
response.setHeader("Access-Control-Allow-Headers","x-requested-with,content-type");

2. AngularJS端使用$http.post(),同时设置请求头信息

$http.post('http://localhost/ajax/getAllIndustryCategoty.pt',{languageColumn:'name_eu'},{'Content-Type':'application/x-www-form-urlencoded'}).success(function(data){
$scope.industries = data;
});

四、实现方式

跨域方式一【JSONP】:

方法一:

$http.jsonp("http://localhost/sitesettings/getBadgeInfo.pt?jsonp=JSON_CALLBACK&siteid=137bd406").success(function(data){ ... });
// The name of the callback should be the string JSON_CALLBACK.

方法二【返回值,需要使用对应callback方法接收,但如何置于$scope?】:

$http.jsonp("http://localhost/sitesettings/getBadgeInfo.pt?jsonp=badgeabc&siteid=137bd406");
function badgeabc(data){ ... }
public String execute() throws Exception {
String result = FAIL;
response.setHeader("", "");
SiteHandlerAction siteHandlerAction = (SiteHandlerAction)BeansFactory.getBean(SiteHandlerAction.class);
BadgeHandlerAction badgeHandlerAction = (BadgeHandlerAction)BeansFactory.getBean(BadgeHandlerAction.class);
if("".equals(siteid) || siteid == null || StringUtils.isBlank("jsonp")){
result = FAIL;
}else{
Site site = siteHandlerAction.find(siteid);
UserBadgeStatus userBadgeStatus = badgeHandlerAction.getUserBadgeStatus(site.getId());
if(userBadgeStatus != null){
result = "{\"t\":"+userBadgeStatus.getStyle()+",\"l\":"+userBadgeStatus.getSuspend_location()+",\"s\":"+site.getId()+"}";
JSONObject jsonObj = JSONObject.fromObject(result);
String json = jsonObj.toString();
result = jsonp + "(" + json + ")";
}
}
PrintWriter write = response.getWriter();
write.print(result);
write.flush();
write.close();
return NONE;
}

跨域方式二【$http.get()】:

function getAdustryController($scope,$http){
$http.get('http://localhost/ajax/getAllIndustryCategoty.pt?languageColumn=name_eu').success(function(data){
$scope.industries = data;
});
}

跨域方式三【$http.post()】:

function getAdustryController($scope,$http){
$http.post('http://localhost/ajax/getAllIndustryCategoty.pt',{languageColumn:'name_eu'},{'Content-Type':'application/x-www-form-urlencoded'}).success(function(data){
$scope.industries = data;
});
}
// java端支持跨域请求
public String execute(){
response.setHeader("Access-Control-Allow-Origin", "*"); //允许哪些url可以跨域请求到本域
response.setHeader("Access-Control-Allow-Methods","POST"); //允许的请求方法,一般是GET,POST,PUT,DELETE,OPTIONS
response.setHeader("Access-Control-Allow-Headers","x-requested-with,content-type"); //允许哪些请求头可以跨域 SiteHandlerAction SiteHandler = (SiteHandlerAction) BeansFactory.getBean(SiteHandlerAction.class);
List list = SiteHandler.getAllIndustryCategory(); //所有的分类集合
JSONArray jsonArray = JSONArray.fromObject(list); //将list转为json
String json = jsonArray.toString(); //转为json字符串
try {
PrintWriter write = response.getWriter();
write.print(json);
write.close();
} catch (IOException e) {
e.printStackTrace();
}
return NONE;
}

http://www.ruanyifeng.com/blog/2016/04/cors.html

angular.js跨域post解决方案的更多相关文章

  1. js跨域及解决方案

    本文出自:http://www.cnblogs.com/oneword/archive/2012/12/03/2799443.html 1.什么是跨域 我们经常会在页面上使用ajax请求访问其他服务器 ...

  2. js跨域请求解决方案

    什么是跨域? 跨域是指一个域下的文档或脚本试图去请求另一个域下的资源,这里跨域是广义的. 广义的跨域: 1.) 资源跳转: A链接.重定向.表单提交 2.) 资源嵌入: <link>.&l ...

  3. js跨域问题解决方案

     跨域:当协议.域名.端口号任何一个不相同时,叫称为跨域.   HTML5  CORS(cross-origin-resource-sharing)跨域资源共享: 原理:当需要访问跨域的资源时,可以通 ...

  4. js跨域问题解释 使用jsonp或jQuery的解决方案

    js跨域及解决方案 1.什么是跨域 我们经常会在页面上使用ajax请求访问其他服务器的数据,此时,客户端会出现跨域问题. 跨域问题是由于javascript语言安全限制中的同源策略造成的. 简单来说, ...

  5. Atitit.js跨域解决方案attilax大总结 后台java php c#.net的CORS支持

    Atitit.js跨域解决方案attilax大总结 后台java php c#.net的CORS支持 1. 设置 document.domain为一致  推荐1 2. Apache 反向代理 推荐1 ...

  6. vue.js及H5常见跨域问题解决方案

    一.原生H5跨域问题解决方案 1.live-server 代理解决 首先在有node.js环境下,打开命令行工具,输入 npm install live-server -g 全局安装全局安装 live ...

  7. js跨域请求jsonp解决方案-最简单的小demo

    这里说的js跨域是指通过js在不同的域之间进行数据传输或通信,比如用ajax向一个不同的域请求数据,或者通过js获取页面中不同域的框架中(iframe)的数据.只要协议.域名.端口有任何一个不同,都被 ...

  8. js跨域原理及解决方案

    方法一:jsonp函数 在HTML DOM中,Script标签是可以跨域访问服务器上的数据的.因此,可以指定script的src属性为跨域的url,基于script标签实现跨域.script标签本身就 ...

  9. C#进阶系列——WebApi 跨域问题解决方案:CORS

    前言:上篇总结了下WebApi的接口测试工具的使用,这篇接着来看看WebAPI的另一个常见问题:跨域问题.本篇主要从实例的角度分享下CORS解决跨域问题一些细节. WebApi系列文章 C#进阶系列— ...

随机推荐

  1. kinect (oldest one) (libfreenect with py_kinect) on linux ubuntu14.04 x64

    freenect libs Where is the resource? Here :P : https://github.com/OpenKinect/libfreenect To make sur ...

  2. LAMP on ubuntu12.04 PHP, Apache2, MySQL, Linux ( with phpmyadmin installed)

    there are several procedure which include: 1. Install the packages sudo apt-get install php5 php5-gd ...

  3. 项目开发之分页---异步分页(ajax)

    PS:前面忘了给大家讲解后台需要做的 ,同步分页的时候,我们只需要定义一个方法,给前台传递一个page对象,前台接收到直接展示即可:异步分页要多一步,首先还是写一个方法,传递初始对象,后面的ajax返 ...

  4. Android- assent和raw的区别

    Android- assent和raw的区别 相同点: 里面的文件在编译的时候都不会被编译成二进制文件,都会原封不动的打包. 不同点: 1.存放的路径不一样,一般assets存放在项目的根目录下,而r ...

  5. 读headFirst设计模式 - 策略模式

    有些人已经解决你的问题了 什么是设计模式?我们为什么要使用设计模式?怎样使用?按照书上的说法和我自己的理解,我认为是这样的:我们遇到的问题其他开发人员也遇到过,他们利用他们的智慧和经验将问题解决了,把 ...

  6. PHPWAMP开启php_stomp.dll的具体方式,php5.6开启stomp的图解过程

    友情提示:其他版本,方式一样的,大家依样画葫芦即可. 首先下载PHP 扩展php_stomp.dll文件,在php官方网站搜索"Stomp",搜索后,如下图 如下图点击" ...

  7. angular1.x 脏检测

    写在前面 双向绑定是angular的大亮点,然后支撑它的就是脏检测.一直对脏检测都有一些理解,却没有比较系统的概念. 以下是我阅读网上博文以及angular高级程序设计的理解与总结. 接收指导与批评. ...

  8. Linux上传与下载(sz-rz)

    linux使用rz和sz命令上传和下载文件! sz命令发送文件到本地: # sz filename rz命令本地上传文件到服务器: # rz 执行该命令后,在弹出框中选择要上传的文件即可. 说明:打开 ...

  9. phpopp

    <?php header("content-type:text/html;charset=utf8"); class lidepeng{ var $name; public ...

  10. 采用rest接口对接而非webservice

    代码示例 public static String queryForCTI(String url){ String targetURL = getCTIurl()+"/"+url; ...