角度发布不发送

时间:2016-04-08 18:57:11

标签: angularjs rest http post

这是我的 index.html 页面:

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>My AngularJS App</title>
  <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/normalize.css">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/main.css">
  <link rel="stylesheet" href="app.css">
  <script src="bower_components/html5-boilerplate/dist/js/vendor/modernizr-2.8.3.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
  <script src="app.js"></script>
</head>
<body>
  <div ng-controller="HomeCtrl">
      <form ng-submit="sendPost()">
        <label>Input id</label>
        <input type="text" ng-model="id" required/>
        <button type="submit">Submit</button>
      </form>
      {{response}}
  </div>
</body>
</html>

这是 app.js

'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [])
.controller('HomeCtrl', function($scope, $http) {
    $scope.id = "";
    $scope.response = "";
    $scope.sendPost = function() {
        var userDetails = [{"userId":"23848348", "type":"CUSTOMER"}];
        var request = {
            method: 'POST',
            url: 'http://thisisatest.testhost.com/userInfo',
            headers: {
                'Content-Type': 'application/json',
                'id':$scope.id
            },
            data: $.param({
                json: JSON.stringify({
                    'code':'8388',
                    'userDetails': userDetails
                })
            })
        }
        $http(request)
            .success(function(data, status, headers, config){
                /*called for result & error because 200 status*/
                if (data.result) {
                    $scope.response = data.result;
                } else if (data.error) {
                    //handle error here
                }
            })
            .error(function(data, status, headers, config){
                /*handle non 200 statuses*/
            });
    }
})

这里是json请求体的样子:

{
   "code":"8388",
   "userDetails": [
        {          
            "userId": "23848348",        
            "type": "CUSTOMER"
        }
   ]
}

但是当我在文本框中输入一个id并点击提交时,我看不到响应区域中打印的任何内容。知道我在这里做错了吗?

1 个答案:

答案 0 :(得分:0)

我发现了这个问题。请求的数据部分应该是:

data: {
    'code':'8388',
    'userDetails': userDetails
}