AngularJS&$http服務Post請求前後臺數據交互

$http服務實現簡單表單提交實例Demo

通過Angularjs的$http服務post方式提交表單,並請求後臺進行數據交互

Question:

  1. $http服務Post跨域
  2. 轉換請求和響應

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跨域

  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");
  1. AngularJS端使用$http.post(),同時設置請求頭信息

實現:


AngularJS的$Http服務Request格式轉換方法

angular作爲Single Page Application推薦的交互方式是基於jsonajax調用。
但有時服務是基於非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提交方式。

參考博文

AngularJS $http 異步後臺無法獲取請求參數

AngularJS的$http的跨域問題

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章