2014-07-23 96 views
0

我正在使用$ http發佈一個angularjs變量,我確實收到了servlet的doPost方法中的JSON等價物。當我在servlet的響應中寫入JSON時,會調用$ http.success(data,status,header,config)。但是,當我將'data'分配給一個angularjs變量時,沒有值get被賦值給該變量。嘗試使用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成功函數中的doPost()方法獲取JSON。這是否是正確的做法? Angularjs自動將接收到的JSON轉換爲javascript對象類型,因此我必須能夠將'data'直接指定給$ scope.result。

如果有人能指點我正確的方向,這將是偉大的。

+0

'data'是包含一個屬性'data'的對象。該屬性擁有你想要的。您可能希望將'data'重命名爲'response'。如果你這樣做,你可以分配'response.data'(不使用'JSON.parse()' – Sprottenwels

+0

我嘗試了你的建議,以下是控制檯輸出: 響應:未定義 狀態:200 頭文件:function(name) { 如果(headersObj!)headersObj = parseHeaders(頭); 如果(名稱){ 返回headersObj [小寫(名稱)] ||空; } 返回headersObj; } common.js:113 配置:[對象對象] –

+0

在您的成功函數中,添加'console.dir(data)'並將回覆添加到您的問題請 – Sprottenwels

回答

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("&"); 
    } 
}) 
+0

請問什麼是應該做的 – Sprottenwels

+0

要發送的數據爲形式的數據,而不是請求負載 – Raghavendra

+0

哪種方法'queryparams'引用 – Eric