2017-02-22 31 views
0

我在論壇和AngularJS上都很新。用angularJS創建一個函數

我正在嘗試向REST服務器發送請求。我用這個功能

$scope.submitForm = function() { 
    var url = 'http://localhost:8080/Server/config/start'; 

    var request = $http({ 
    method: 'POST', 
    url: url, 
    params: { 
     name: 'test' 
    } 
    }); 

    request.success(
    function() { 
     //alert('it succeeded'); 
    } 
); 

    request.error(
    function() { 
     // alert('it didnt work'); 
    } 
); 

}; 

代碼不是在服務器端運行正常的,因爲有些系列化的東西。我發現在論壇上一個帖子說建議使用此功能,而不是

$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: { 
    username: $scope.userName, 
    password: $scope.password 
    } 
}).success(function() {}); 

我不知道如何使用此功能,我的代碼,我想這個代碼

$scope.submitForm = function() { 
    var url = 'http://localhost:8080/Server/config/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: 'test' 
     } 
    }).success(function() {}); 

,但我由於});而出現錯誤。有人可以幫我格式化和修復代碼嗎?

+0

什麼是服務器端期望 - 表單數據或原始數據? –

+0

只需添加一個結束大括號來關閉'$ scope.submitForm'函數 – Fissio

+0

我認爲表單數據。不是json。我在球衣上使用@FormParam。 –

回答

0
$scope.submitForm = function() { 
    var url = 'http://localhost:8080/Server/config/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: 'test'}}).success(function() {}); 
} // you need a '}' here. 

你也可以試試$ http這種方法的post方法。

$http.post('url', data) 
    .success(function(data, status, headers) { //success callback }) 
    .error(function(data, status, headers) { //error callback }); 
相關問題