2017-04-24 48 views
1

我有以下REST服務,我必須對POST方法訪問, 我可以通過jQuery訪問,但我不知道如何與AngularJSv1

<string xmlns = "http://schemas.microsoft.com/2003/10/Serialization/"> 
    <script id = "tinyhippos-injected" /> 
     { 
     "volumeResult": { 
      "gyydt": "9771241.17704773", 
      "gytotal": "29864436.1770477", 
      "gybudgeted": "29864436.1770477", 
      "lyydt": "10197350", 
      "lytotal": "27859381", 
      "lybudgeted": "10197350", 
      "cyytd": "6992208", 
      "lastUpdate": "March-2017" 
     }, 
     "valueResult": { 
      "gyydt": "26862094", 
      "gytotal": "68217952", 
      "gybudgeted": "68232952", 
      "lyydt": "0", 
      "lytotal": "0", 
      "lybudgeted": "0", 
      "cyytd": "68217952", 
      "lastUpdate": "March-2017" 
     }, 
     "trucksResult": { 
      "gyydt": "165951", 
      "gytotal": "497879", 
      "gybudgeted": "497879", 
      "lyydt": "168822", 
      "lytotal": "468814", 
      "lybudgeted": "168822", 
      "cyytd": "119442", 
      "lastUpdate": "March-2017" 
     } 
    } 
</string> 

這裏做到這一點是我controller.js

angular.module('starter.controllers', []) 
.controller('DashCtrl', ['$scope', '$http', function ($scope, $http) { 

    $http({ 
     //headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}, 
     headers: {'Content-Type' : 'application/json'}, 
     url: 'https://myurl../api/getHPData', 
     method: 'POST', 
     // data: data, 
     params: { 
      "stationId": 263, 
      "crusherId": 27, 
      "monthYear": '2016-04' 
     } 
    }) 
    .then(function (response) { 
       console.log(response); 
    }) 
// I don't have to use .success and .error function as they are [depricated][2] 

//.success(function (data, status, headers, config) { 

//  $scope.greeting = data; 
//  var Result = JSON.stringify(data); 
//  var Result = JSON.parse(data); 
//}) 
//.error(function (error, status, headers, config) { 
// console.log("====================== Error Status is: " + error); 
// console.log("====================== Status is: " + status); 
// console.log("====================== Error occured"); 
//}) 
}]) // eof controller DashCtrl 

.controller('MapsCtrl', function($scope) {}) 

.controller('AccountCtrl', function($scope) { 
    $scope.settings = { 
    enableFriends: true 
    }; 
}); 

什T I想是的值: 「volumeResult」> 「gytotal」

問題:

  1. 它總是返回:

Object {data: "{"result":"false"}", status: 200, config: Object, statusText: "OK", headers: function}

  1. 當我通過monthYear不帶引號它處理(算術)它作爲(2016-04 = 2012)

  2. 由於服務是POST但是當我分析它在Chrome Developers Tool,所以我得到:(查詢字符串,這並不意味着是POST )

ionic.bundle.js:25005 XHR finished loading: POST " https://myurl../api/getHPData?crusherId=27&monthYear=2016-4&stationId=263 "

可能的解決方案: 要麼我使用錯誤的頭:

headers: { 
     'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 
     'Accept':  'application/json' 
     }, 

或標題可能是,

headers: { 
     'Content-Type': 'application/json', 
     'Accept':  'application/json' 
     }, 

或按我的朋友說:

When I change your code to use the code above, I get this error: "{"Message":"The requested resource does not support http method 'OPTIONS'."}" Which means that there is a CORS (Cross-origin Resource Sharing) issue. Chrome is trying to make a "preflight" request to allow CORS, but the server doesn't know what to do with it.

但我不認爲這是因爲這是我收到:

Object {data: "{"result":"false"}", status: 200, config: Object, statusText: "OK", headers: function}

來自服務器。注意到:{"result":"false"}是服務器在未找到數據時顯示的消息或您通過錯誤參數。另外,下面的jQuery代碼證明我可以訪問服務器。:)

編輯

jQuery的片段:上面的腳本的

<script> 
$(document).ready(function() { 
     get_homepage_data(263, 27, '2016-04'); 

     function get_homepage_data(stationIds, crusherIds, date) { 
      var url = "https://myurl.."; 
      var data_to_send = { 
       'stationId': stationIds, 
       'crusherId': crusherIds, 
       'monthYear': date 
      }; 

      console.log("Value is: " + JSON.stringify(data_to_send)); 
      //change sender name with account holder name 
      //  console.log(data_to_send) 
      $.ajax({ 
       url: url, 
       method: 'post', 
       dataType: 'json', 
       //contentType: 'application/json', 
       data: data_to_send, 
       processData: true, 
       // crossDomain: true, 
       beforeSend: function() { 
       } 
       , complete: function() {} 
       , success: function (result1) { 

        // I know I can do it in one line but lazy enough to edit it here :p 
        var Result = JSON.parse(result1); 
        var value_data = Result["valueResult"]; 
        var foo = value_data["gyydt"]; 

        console.log("Log of foo is: " + foo); 

        var foo2 = 0; 
        // 10 lac is one million. 
        foo2 = foo/1000000 + ' million'; 

        console.log(JSON.stringify(value_data["gyydt"]) + " in million is: " + foo2); 
       } 
       , error: function (request, error) { 
        return false; 
       } 
      }); 
     } 
    }); // eof Document. Ready 
</script> 

輸出爲腳本是:

Value is: {"stationId":263,"crusherId":27,"monthYear":"2016-04"} XHR finished loading: POST " https://myurl../api/getHPData ". Log of foo is: 26862094 "26862094" in million is: 26.862094 million Which is indeed perfect. :)

+1

'當我通過monthYear不帶引號它處理它(2016-04 = 2012)',因爲它是一個基本的'math'操作。看着'它總是返回',似乎你的後端並沒有回報你所期待的。 –

回答

0

嘗試使用$ HTTP這樣..

$http.post("https://myurl../..",JSON.stringify({ 
      stationId: 263, 
      crusherId: 27, 
      monthYear:'2016-04' 
     })).then(function(res){ 

      console.log(res); 

     }).catch(function(errors){ 
      console.log(errors); 
}) 
+0

它給了我:'Uncaught SyntaxError:missing)在參數列表錯誤後。通過在'.then'之前放置一個')',現在它給了我:'OPTIONS https:// myurl ... 405(Method Not Allowed)','XMLHttpRequest無法加載https:// myurl ...預檢有無效的HTTP狀態代碼405','XHR加載失敗:POST「https:// myurl ...」.','Object {data:null,status:-1,config:Object,statusText:「」,headers:功能}' – fWd82

0

我得到了答案。 Whao。

謝謝georgeawg他的回答:

他說:自動

$http({ 
    headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}, 
    url: 'https://myurl..', 
    method: 'POST', 
    transformRequest: $httpParamSerializer, 
    transformResponse: function (x) { 
     return angular.fromJson(angular.fromJson(x)); 
    }, 
    data: { 
     "stationId": 263, 
     "crusherId": 27, 
     "monthYear": '2016-04' 
    } 
}) 
    .then(function(response) { 
    console.log(response); 
    $scope.res = response.data; 
    console.log($scope.res); 
}); 

通常情況下,$http服務:

當發佈是URL編碼形式的數據,轉換與$httpParamSerializer service請求解析來自JSON編碼對象的結果,但此API正在返回已從對象中雙重序列化的字符串transformRespons e函數修復了這個問題。

現在我能得到的gytotal值:

var myData = parseFloat(response.data.valueResult.gytotal); 
    console.log(myData); 
相關問題