4

scalatra サーブレットにデータを投稿する angularJS フォームがあります。フォームが送信されると、scalatra サーブレットでフォーム パラメータを取得できません。

以下は私のコードです

AngularJS

$scope.createUser = function() {
    $http.post('/createUser',{name:$scope.name,email:$scope.email,pwd:$scope.pwd}).
        success(function(data, status, headers, config) {
            alert("success " + data)
        }).
        error(function(data, status, headers, config) {
            alert("failure =>" +data)
        });
 };         });
 };     

HTMLフォーム

<form ng-controller="UserController">
            <legend>Create User</legend>

            <label>Name</label>
            <input type="text" id="name" name="name" ng-model="name" placeholder="User Name">

            <label>Email</label>
            <input type="text" id="email" name="email" 
                ng-model="email" placeholder="ur email here">

            <label>Password</label>
            <input type="text" id="pwd" name="pwd" 
                ng-model="pwd" placeholder="ur own pwd here">

            <button ng-click="createUser()" class="btn btn-primary">Register</button>
        </form>

スカラトラ サーブレット

post("/createUser") {
    println(params("name")) 
}

アプリを実行してフォームから送信しようとすると、このエラーが発生します

エラー 500 キーが見つかりません: 名前 (firebug lite から取得)

何か不足している場合や、これを行う別の方法がある場合はお知らせください

4

4 に答える 4

4

2 つの変更:

  1. 「ng-submit」イベントを使用します。
  2. ng-models をオブジェクト自体の中に入れて、オブジェクトをポストに送信するだけです。

HTML:

<div ng-controller="UserController">
  <form ng-submit="createUser()">
    <input type="text" ng-model="user.name">
    ...
    <input type="email" ng-model="user.email">
    ...
  </form>
</div>

JS:

function UserController($scope, $http) {
  $scope.user = {};
  $scope.createUser = function() {
    $http.post('/createUser', $scope.user);
  }
}
于 2012-10-10T19:46:18.440 に答える
3

以下のコードは、http投稿自体にヘッダー情報を追加することでこれを解決しました

$scope.createUser = function() {
$http({
method: 'POST',
url: '/createUser',
data: 'name=' + $scope.user.name + '&email=' +$scope.user.email,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

}

他の誰かが他のより良いアプローチを持っている場合は、提案を投稿してください。

于 2012-10-11T14:18:31.400 に答える
0

私も同様の問題を抱えていました。データはサーバーに正しく投稿されていましたが、通常の $_POST または $_REQUEST で POST データを受信できませんでした

しかし、以下は私のために働いた

$data = json_decode(file_get_contents("php://input"));
于 2013-06-14T07:58:15.483 に答える
0

This will be late to answer. Anyway, I assume this will help someone else and therefore, I post my answer.

If you want to read the body of request when the request is submitted as POST , you may get it with the reader of HttpRequestas following.

      BufferedReader reader = request.getReader();
      String line = null;
      while ((line = reader.readLine()) != null)
      {
        sb.append(line);
      }

 String requestBody = sb.toString();

Hope this will helpful.

于 2015-04-09T14:42:16.363 に答える