gpt4 book ai didi

javascript - 如何通过POST方法发送json文件并在servlet上接收

转载 作者:行者123 更新时间:2023-12-03 08:23:48 25 4
gpt4 key购买 nike

我正在尝试发送一个 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());
....

最佳答案

无需执行数据:JSON.stringify(clientData)。 Angular 会自动格式化为 JSON。

Controller 代码:

    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>

关于javascript - 如何通过POST方法发送json文件并在servlet上接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33638221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com