$http服務實現簡單表單提交實例Demo
通過Angularjs的$http服務post方式提交表單,並請求後臺進行數據交互
Question:
- $http服務Post跨域
- 轉換請求和響應
Jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="zh-CN">
<head >
<title>Submit Data</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css">
<script src="js/angular.min.js"></script>
</head>
<body ng-app="myApp" class="container-fluid">
<form class="form form-horizontal" ng-controller="userFrom" ng-submit="submitInfo()">
<div>
<input type="text" name="name" ng-model="$parent.name"/>
</div>
<div>
<input type="text" name="pwd" ng-model="$parent.pwd"/>
</div>
<button type="submit" class="btn-default">submit</button>
</form>
</body>
<html>
JS(AngularJS方式):
<script>
var app = angular.module('myApp',[]);
app.controller('userFrom',function ($scope,$http){
$scope.submitInfo = function () {
$http({
method:'post',
url:'${pageContext.request.contextPath}/user/getUserInfo',
data:{name:$scope.name,pwd:$scope.pwd},
headers:{'Content-Type': 'application/x-www-form-urlencoded'},//
transformRequest: function(obj) {
var str = [];
for(var p in obj){
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
}).success(function(req){
console.log(req);
})
};
});
</script>
Java:
public class UserInfoServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
System.out.println(name+pwd);
//if 驗證是否拿到Angularjs$http服務Post提交的數據,
if (name.equals("root")&&pwd.equals("root")){
System.out.println("Login Success!");
//數據提交成功!
}else
{
System.out.println("Login Failure!");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
瀏覽器輸出:
後臺輸出打印信息
$http服務Post跨域
- 在服務器端設置允許在其他域名下訪問,及響應類型、響應頭設置
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods","POST");
response.setHeader("Access-Control-Allow-Headers","x-requested-with,content-type");
- AngularJS端使用$http.post(),同時設置請求頭信息
實現:
AngularJS的$Http服務Request格式轉換方法
angular作爲Single Page Application推薦的交互方式是基於json的ajax調用。
但有時服務是基於非json提交方式(或是常規表單(form)提交,或者其他自定義數據格式),那麼我們只能改變AngularJS內部$http服務默認的request/response格式。
1. 對於單獨的$http服務request設置:
$http.post("/url", {
id: 1,
name: "DuebassLei"
}, {
transformRequest: function(request) {
return $.param(request);
}
});
這裏利用jQuery的$.param進行表單提交方式的格式轉化,所以我們能夠看見的request body 爲:
id = 1 & name = DuebassLei
2. 對於整個app的http request設置:
如果我們需要對整個http的數據轉化格式進行設置,那麼可以選用在config階段對$httpProvider默認行爲進行設置:
var module = angular.module('myApp');
module.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = function(data) {
//使用jQuery的param方法把JSON數據轉換成字符串形式
return $.param(data);
};
});
這樣我們就可以輕易的轉化爲form提交方式。