【问题标题】:Angularjs parsses non JSON POST responseAngularjs 解析非 JSON POST 响应
【发布时间】:2017-02-23 06:09:03
【问题描述】:

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

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

AngularJS 尝试解析对 json 的响应,但出现解析错误

错误:JSON.parse:JSON 的第 1 行第 1 列出现意外字符 数据

这是我的 Angular 代码

$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)
});
} 

【问题讨论】:

    标签: angularjs angular-http


    【解决方案1】:

    你需要重写转换响应函数

    $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)
    });
    } 
    

    【讨论】:

    • 谢谢,工作完美。只是一个小的语法错误,缺少]
    猜你喜欢
    • 2018-11-22
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    相关资源
    最近更新 更多