angularjs $ http成功数据参数不返回正确的对象

时间:2014-07-23 08:40:18

标签: json angularjs servlets post

我使用$ http来POST一个angularjs变量,我确实在servlet的doPost方法中收到了JSON等价物。当我在servlet的响应中编写JSON时,会调用$ http.success(data,status,header,config)。但是当我将'data'分配给angularjs变量时,没有赋值赋值给变量。尝试使用JSON.parse(数据),但没有用。以下是代码段。

AngularJS

$scope.result = {
    title: "",
    subject: "",
    summary: "",
    body: "",
    extra: ""
};

$http.post(url, JSON.stringify(obj)).
success(function(data, status, headers, config){
        $scope.result = JSON.parse(data);
        console.log("data: " + data);
        console.log("status: " + status);
        console.log("headers: " + headers);
        console.log("config: " + config);
    })
    .error(function(data, status, headers, config){
        $scope.result = JSON.parse(data);
        console.log("data: " + data);
        console.log("status: " + status);
        console.log("headers: " + headers);
        console.log("config: " + config);
    });

接收响应时的控制台输出如下

data: [object Object]
status: 200 
headers: function (name) {
   if (!headersObj) headersObj =  parseHeaders(headers);

   if (name) {
      return headersObj[lowercase(name)] || null;
   }

   return headersObj;
  }
config: [object Object]

以下是servlet的代码片段。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        System.out.println("doPost called");
        response.getWriter().write("{"title":"Transaction Status","subject":"Congratulations!!","summary":"Successfully received your request, below is your Transaction ID","body":"5a85fc3b303d47dca6514b707442f2cd","extra":"Please save this transaction ID for future reference"}");
    }

我无法从angularjs success函数中获取从doPost()方法发送的JSON。这是正确的做法吗? Angularjs会自动将收到的JSON转换为javascript对象类型,因此我必须能够将'data'直接分配给$ scope.result。

如果有人能指出我正确的方向,那就太棒了。

1 个答案:

答案 0 :(得分:0)

使用此:

$http.post(url, $.param(obj), {
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
})

如果您不想使用jQuery $ .param,则可以使用替代

$http.post(url, obj, {
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    }
})