我正在尝试发送一个json对象,例如:{id: 1, firstName: Paul, lastName: Lambert}
问题是我在json对象上得到一个NULL或错误的参数
testProjectApp.factory('updateClient', function($http, $q) {
return {
postClient: function (clientData) {
var deferred = $q.defer();
alert(clientData.firstName);
$http({
url: 'UpdateClient',
method: "POST",
contentType: 'application/json',
data: JSON.stringify(clientData)
}).success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
};
});
并在servlet中:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject json;
try {
System.out.println(request.getParameter("data"));
json=new JSONObject(request.getReader());
....
答案 0 :(得分:1)
无需data: JSON.stringify(clientData)
。 Angular会自动格式化为JSON。
控制器代码:
function updateClient($scope, $http) {
$scope.client = {};
$scope.clientUpdate = function() {
$http({
method : 'POST',
url : '/UpdateClient',
data : $scope.client
}).success(function(data) {
// do something if the request is success
}).error(function(data) {
// do something if the request is fail
});
}
Servlet代码:
JSONObject jsnObjt = new JSONObject(request.getParameter("data"));
Iterator it = jsnObjt.keys();
while(it.hasNext())
{
String key = it.next();
Object ob = jsnObjt.get(key);
String user = jsnObjt.get("client");
}
关于您的要求的示例HTML:
<form ng-controller="updateClient" ng-submit="clientUpdate()">
<input type="text" id="id" name="id" ng-model="client.id">
<input type="text" id="fname" name="fname" ng-model="client.firstName">
<input type="text" id="lname" name="lname" ng-model="client.lastName">
<button type="submit" class="btn">Update</button>
</form>