2017-02-22 128 views
0

我向服务器发送POST请求。作为响应,服务器发送一个http代码和一个纯文本。Angularjs解析非JSON POST响应

return Response.status(200).entity("Started").build(); 

AngularJS尝试解析为JSON响应,我得到一个解析错误

Error: JSON.parse: unexpected character at line 1 column 1 of the JSON data

这是我的角码

$scope.submitForm = function() { 
    var url = 'http://localhost:8080/Server/server/start'; 
    var request = $http({ 
    method: 'POST', 
    url: url, 
    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('&'); 
    }, 
    data: {name: $scope.name}}).then(function(html) { 
    //success callback code 
    //console.log(html) 
}, function(html) { 
    //error callback code 
    //console.log(html) 
}); 
} 

回答

0

你需要重写变换响应函数

$scope.submitForm = function() { 
    var url = 'http://localhost:8080/Server/server/start'; 
    var request = $http({ 
    method: 'POST', 
    url: url, 
    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('&'); 
    }, 
    transformResponse: [ 
    function (data) { 
     return data; 
    }, 
    ], 
    data: {name: $scope.name}}).then(function(html) { 
    //success callback code 
    //console.log(html) 
}, function(html) { 
    //error callback code 
    //console.log(html) 
}); 
} 
+0

Thanx,工作完美。只是一个小的语法错误,]缺少 – user567

+0

@ user567好消息,并对语法错误感到抱歉 –