2016-11-10 129 views
0

使用方法POST時收到此錯誤。請幫幫我。未捕獲的語法錯誤意外的令牌{在JSON中

angular_min.js:114 SyntaxError: Unexpected token { in JSON at position 71 
    at JSON.parse (<anonymous>) 
    at wc (angular_min.js:16) 
    at cc (angular_min.js:88) 
    at angular_min.js:89 
    at n (angular_min.js:7) 
    at hd (angular_min.js:89) 
    at c (angular_min.js:91) 
    at angular_min.js:126 
    at m.$eval (angular_min.js:141) 
    at m.$digest (angular_min.js:138) 

我的代碼: VAR JSON = {PARAMETER_NAME: 「量」, 「PARAMETER_VALUE」:$ scope.it.amount};

  var arr=[]; 
     arr.push(json); 
     $scope.object={formula:$scope.it.formula_saving_point}; 
     $scope.companyTemp={company_id:com_id}; 
     var url = API_URL + "cumulative_point_formula";  
     var cmd = "check_formula"; 
     var jsonFinal = JSON.stringify({json_parameter: JSON.parse(JSON.stringify(arr)), 
      company: JSON.parse(JSON.stringify($scope.companyTemp)), 
      cumulative_point_formula: JSON.parse(JSON.stringify($scope.object))}); 

此日誌jsonFinal

{"json_parameter":[{"parameter_name":"amount","parameter_value":"111111111"}],"company":{"company_id":40743},"cumulative_point_formula":{"formula":"amount/10000"}} 

這是POST方法:

$http({ 
       method: 'POST', 
       url: url, 
       data: $.param({cm: cmd, dt: jsonFinal}), 
       headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
      }).success(function (response) { 
       console.log("success"); 
}); 

如何修復這個bug?

+0

你是否故意在這個問題中重複你的代碼? – Claies

+1

'JSON.parse(JSON.stringify($ scope.companyTemp))'呃...爲什麼? –

+0

@Derek朕會功夫:老派克隆對象的方式。在很多瀏覽器中,它仍然是最快的方法 – slebetman

回答

0

如果你仔細看看你的錯誤它源於JSON.parse,而不是$ HTTP。我相信是由該行

var jsonFinal = JSON.stringify({json_parameter: JSON.parse(JSON.stringify(arr)), 
    company: JSON.parse(JSON.stringify($scope.companyTemp)), 
    cumulative_point_formula: JSON.parse(JSON.stringify($scope.object))}); 

,其中該塊這裏代碼非常冗餘導致此錯誤:

JSON.parse(JSON.stringify($scope.companyTemp)) 

字符串化>解析會導致同$範圍。 companyTemp以及其他,並且與此相同:

var jsonFinal = JSON.stringify({ 
     json_parameter: arr, 
     company: $scope.companyTemp, 
     cumulative_point_formula: $scope.object 
    }); 

JSON.parse JSON字符串轉換爲有效的JavaScript對象

JSON.stringify JavaScript對象轉換爲字符串

如果仍然產生一個錯誤,我相信這三個改編之一,$ scope.companyTemp$ scope.object具有無效值。

希望可以幫到

+0

嗨Preenz,我知道了,我嘗試你的方式,但我解決它。我再次收到「SyntaxError:Unexpected token {在位置71的JSON中」。但我console.log jsonFinal並在POSTMAN中測試它。它運行。結果是:[ { 「結果」:「1」 } ] 可以再次幫助我嗎? – John

+0

我不能完全猜測這些變量裏面有什麼,但一定要檢查這些是否有對象或數組值,如果其中一個是**字符串**,** JSON.stringify **會炸燬。檢查出這些變量** arr **,** $ scope.companyTemp **,** $ scope.object **,** $ scope.it.formula_saving_point **,** com_id ** – masterpreenz

+0

哦,我知道並且解決它。非常感謝你。 – John

相關問題