如果出现错误,如何更改http post请求的url

时间:2016-09-29 15:45:55

标签: javascript angularjs http post

以下是处理表单的功能

            $scope.processForm = function () {

                var url = 'http://localhost:8080/tickets/'

                $http({
                    method: 'POST',
                    headers: {'Content-Type': 'application/json; charset=UTF-8'},
                    url: url,
                    data: JSON.stringify($scope.formData)
                }).then(function successCallback(response) {
                    //log
                    console.log("ticket purchased");

                }, function errorCallback(response) {
                    var requestID = JSON.stringify(response.data.requestID);
                    console.log("purchase failed");
         });

如果出现错误,我想要将requestID附加到网址的末尾。

如果有错误,那么一旦他们再次提交,网址就会更改以下内容:

 var url = 'http://localhost:8080/tickets/'+ requestID

2 个答案:

答案 0 :(得分:1)

您希望将requestID附加到您要提交数据的网址的末尾,对吗?

一种选择是在$ scope上存储URL或requestID。

$scope.url = 'http://localhost:8080/tickets/';

$scope.processForm = function () {

            $http({
                method: 'POST',
                headers: {'Content-Type': 'application/json; charset=UTF-8'},
                url: $scope.url,
                data: JSON.stringify($scope.formData)
            }).then(function successCallback(response) {
                //log
                console.log("ticket purchased");

            }, function errorCallback(response) {
                var requestID = JSON.stringify(response.data.requestID);
                $scope.url = 'http://localhost:8080/tickets/' + requestID;
                console.log("purchase failed");
     });

答案 1 :(得分:0)

我想出了如何实现我想要的最终目标。我在$ scope上保存了url和requestID。

if ($scope.requestID == null) {
    $scope.url = 'http://localhost:8080/tickets/';
} 
else if ($scope.requestID !== null && $scope.firstTransaction == null) {

    $scope.firstRequest = $scope.requestID;

    console.log("first transaction id = " + $scope.requestID)

    $scope.url = 'http://localhost:8080/tickets/' + $scope.firstRequest;

}

$scope.processForm = function() {

        $http({
            method: 'POST',
            headers: {
                'Content-Type': 'application/json; charset=UTF-8'
            },
            url: $scope.url,
            data: JSON.stringify($scope.formData)
        }).then(function successCallback(response) {
            //log
            console.log("ticket purchased");

        }, function errorCallback(response) {
            var requestID = JSON.stringify(response.data.requestID);
            $scope.url = 'http://localhost:8080/tickets/' + requestID;
            console.log("purchase failed");
        });